Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registering a custom Spree Calculator not working

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.

like image 941
Mike Jaffe Avatar asked May 24 '13 05:05

Mike Jaffe


1 Answers

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
like image 137
gmacdougall Avatar answered Sep 28 '22 05:09

gmacdougall