You want to calculate the cost to ship any item with FedEx or UPS. This is useful if you e running an online store.
FedEx and UPS provide web services that can query information on pricing as well as retrieve shipping labels. The logic for using these services has been encapsulated within the shipping gem:
require ubygems require shipping ship = Shipping::Base.new( :fedex_url => https://gatewaybeta.fedex.com/GatewayDC, :fedex_account => 123456789, :fedex_meter => 387878, :ups_account => 7B4F74E3075AEEFF, :ups_user => username, :ups_password => password, :sender_zip => 10001 # Its shipped from Manhattan. ) ship.weight = 2 # It weighs two pounds. ship.city = Portland ship.state = OR ship.zip = 97202 ship.ups.price # => 8.77 ship.fedex.price # => 5.49 ship.ups.valid_address? # => true
If you have a UPS account or a FedEx account, but not both, you can omit the account information you don have, and instantiate a Shipping::UPS or a Shipping::FedEx object.
You can either specify your account information during the initialization of the object (as above) or in a YAML hash. Its similar to the payment library described in Recipe 16.8. If you choose to use the YAML hash, you can specify the account information in a file called .shipping.yml within the home directory of the user running the Ruby program:
fedex_url: https://gatewaybeta.fedex.com/GatewayDC fedex_account: 1234556 fedex_meter: 387878 ups_account: 7B4F74E3075AEEFF ups_user: username ups_password: password
But your directory is not a good place to keep a file being used by a Rails application. Heres how to move the .shipping file into a Rails application:
ship = Shipping:: FedEx.new(:prefs => "#{RAILS_ROOT}/config/shipping.yml") ship.sender_zip = 10001 ship.zip = 97202 ship.state = OR ship.weight = 2 ship.price > ship.discount_price # => true
Notice the use of ship.discount_price to find the discounted price; if you have an account with FedEx or UPS, you might be eligible for discounts.
Strings
Numbers
Date and Time
Arrays
Hashes
Files and Directories
Code Blocks and Iteration
Objects and Classes8
Modules and Namespaces
Reflection and Metaprogramming
XML and HTML
Graphics and Other File Formats
Databases and Persistence
Internet Services
Web Development Ruby on Rails
Web Services and Distributed Programming
Testing, Debugging, Optimizing, and Documenting
Packaging and Distributing Software
Automating Tasks with Rake
Multitasking and Multithreading
User Interface
Extending Ruby with Other Languages
System Administration