Class: ActiveMerchant::Shipping::ShipmentPacker
- Defined in:
- lib/active_shipping/shipping/shipment_packer.rb
Defined Under Namespace
Classes: ExcessPackageQuantity, OverweightItem
Constant Summary collapse
- EXCESS_PACKAGE_QUANTITY_THRESHOLD =
10_000
Class Method Summary collapse
-
.pack(items, dimensions, maximum_weight, currency) ⇒ Object
items - array of hashes containing quantity, grams and price.
Class Method Details
.pack(items, dimensions, maximum_weight, currency) ⇒ Object
items - array of hashes containing quantity, grams and price.
ex. [{:quantity => 2, :price => 1.0, :grams => 50}]
dimensions - [5.0, 15.0, 30.0] maximum_weight - maximum weight in grams currency - ISO currency code
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
# File 'lib/active_shipping/shipping/shipment_packer.rb', line 15 def self.pack(items, dimensions, maximum_weight, currency) packages = [] return packages if items.empty? items.map!(&:symbolize_keys) if items.sum { |item| item[:quantity].to_i } >= EXCESS_PACKAGE_QUANTITY_THRESHOLD raise ExcessPackageQuantity, "Unable to pack more than #{EXCESS_PACKAGE_QUANTITY_THRESHOLD} packages" end items = items.map { |item| [item] * item[:quantity].to_i }.flatten state = :package_empty while state != :packing_finished case state when :package_empty package_weight, package_value = 0, 0 state = :filling_package when :filling_package item = items.shift item_weight, item_price = item[:grams].to_i, Package.cents_from(item[:price]) if item_weight > maximum_weight raise OverweightItem, "The item with weight of #{item_weight}g is heavier than the allowable package weight of #{maximum_weight}g" end if (package_weight + item_weight) <= maximum_weight package_weight += item_weight package_value += item_price state = :package_full if items.empty? else items.unshift(item) state = :package_full end when :package_full packages << ActiveMerchant::Shipping::Package.new(package_weight, dimensions, :value => package_value, :currency => currency) state = items.any? ? :package_empty : :packing_finished end end packages end |