Finding the Cost to Ship Packages via UPS or FedEx


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 shipping

	ship =
	 :fedex_url =>,
	 :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. = Portland
	ship.state = OR = 97202 # => 8.77 # => 5.49 # => 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_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:: => "#{RAILS_ROOT}/config/shipping.yml")
	ship.sender_zip = 10001 = 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.

See Also

  • Recipe 16.8, "Charging a Credit Card"



Date and Time



Files and Directories

Code Blocks and Iteration

Objects and Classes8

Modules and Namespaces

Reflection and Metaprogramming


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

Ruby Cookbook
Ruby Cookbook (Cookbooks (OReilly))
ISBN: 0596523696
EAN: 2147483647
Year: N/A
Pages: 399 © 2008-2020.
If you may any questions please contact us: