-
Notifications
You must be signed in to change notification settings - Fork 7
Shipping methods
To handle shipping fees in your app, there are existing shippings methods with associated calculators, but you can also create your own easily.
rails g stall:shipping:calculator my_shipping_calculator
Create a Stall::Shipping::Calculator
subclass in your app's lib/
folder, which must define two methods : #available?
and #price
.
class MyShippingCalculator < Stall::Shipping::Calculator
def available?
if cart.shipping_address
cart.shipping_address.country.in?(['FR', 'GB'])
end
end
def price
cart.total_price > 100 ? 0 : 10
end
end
Note : Inside the class you have access to the current
cart
, and theconfig
property which is theStall::ShippingMethod
model instance.
The add it in the stall initializer :
# If the class is not in your app's autoload_paths, require it
require 'my_shipping_calculator'
Stall.configure do |config|
config.shipping.register_calculator :my_shipping_calculator, 'MyShippingCalculator'
end
Restart your server and you should be able to access the shipping method.
Stall comes from an abstract calculator class that handles a specific CSV format to store shipping fees depending on total order weight (rows) and target country (columns).
The CSV should contain comma separated ISO-3166-1 alpha-2 country codes (as provided by the country_select
gem for example) in each top-row cells and max order weight in the first column cells.
The CSV will look like the following :
"FR,GB,DE" | "US,MX" | |
---|---|---|
1 | 5 | 10 |
2 | 10 | 20 |
5 | 15 | 30 |
10 | 30 | 40 |
100 | 40 | 100 |
Your calculator should subclass Stall::Shipping::CountryWeightTableCaclulator
and implement at least the #load_data
method returning a string with a CSV contents. The calculator will parse the CSV with ruby's standard csv
lib.
class MyCSVCalculator < Stall::Shipping::CountryWeightTableCaclulator
def load_data
File.read(Rails.root.join('vendor/shipping_prices.csv'))
end
end
Any country that is not in the list will not be available for this shipping method.