Following the docs on this page... http://guides.spreecommerce.com/developer/calculators.html
I've created a class in models/spree/calculators/
module Spree
class Calculator::ZipTax < Calculator
def self.description
"Calculates Tax Rates From Zipcode in TaxRates Table"
end
def compute(computable)
case computable
when Spree::Order
compute_order(computable)
when Spree::LineItem
compute_line_item(computable)
end
end
def compute_order(order)
zipcode = order.bill_address.zipcode[0,5]
zip = TaxTable.where(:zipcode => zipcode).first
if(zip.present?)
rate = zip.combined_rate
order.line_items.sum(&:total) * rate
else
0
end
end
end
end
And in initializers/spree.rb I've added:
config = Rails.application.config
config.spree.calculators.tax_rates << Spree::Calculator::ZipTax
But I can not get Rails to start. I get undefined method `<<' for nil:NilClass (NoMethodError) on the initializer/spree.rb file.
How do I register a custom Calculator? Using Spree 1.3.2.
You'll need to wrap your configuration in an after_initialize:
in config/application.rb
config.after_initialize do
config.spree.calculators.tax_rates << Spree::Calculator::ZipTax
end
You're encountering an error because the spree calculators haven't been initialized at that point in your application boot process, so you're trying to append the calculator to something that's nil.
Another method, commonly used in Spree extensions is to do the following:
initializer 'spree.register.calculators' do |app|
app.config.spree.calculators.shipping_methods << Spree::Calculator::ZipTax
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With