Registering a special Spree calculator does not work

Following the docs on this page ... http://guides.spreecommerce.com/developer/calculators.html

I created a class in models / spree / calculator /

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 added:

 config = Rails.application.config config.spree.calculators.tax_rates << Spree::Calculator::ZipTax 

But I can not start Rails. I get the undefined `<<method for nil: NilClass (NoMethodError) in the initializer / spree.rb file.

How to register your own calculator? Using Spree 1.3.2.

+6
source share
1 answer

You will need to wrap your configuration in after_initialize:

in config / application.rb

 config.after_initialize do config.spree.calculators.tax_rates << Spree::Calculator::ZipTax end 

You encountered an error because the spree calculators were not initialized at this point in the application loading process, so you are trying to add a calculator to something zero.

Another method commonly used in Spree extensions is as follows:

 initializer 'spree.register.calculators' do |app| app.config.spree.calculators.shipping_methods << Spree::Calculator::ZipTax end 
+9
source

Source: https://habr.com/ru/post/945746/


All Articles