Search code examples
ruby-on-railsspreeruby-on-rails-4.2

Unable to override a method in spree model


I am upgrading my rails and spree to Rails 4.2 and Spree 3.1

I had overriden purchase! method in Payment model

This is how the method is in spree

module Spree
  class Payment < Spree::Base
    module Processing
      def purchase!
        started_processing!
        gateway_action(source, :purchase, :complete)
      end
    end
  end
end

This is how it was overridden in rails 3.2 (and it was working till now)

Spree::Payment::Processing.class_eval do
  def purchase!
    started_processing!
    if source.class == Spree::PurchaseOrder
      gateway_action(source, :authorize, :pend)
    else
      gateway_action(source, :purchase, :complete)
    end
  end
end

But now I am getting the following error with Rails 4.2 and Spree 3.1

/home/deepak/workspace/Project/app/models/spree/payment/processing_decorator.rb:2:in `<module:Spree>': superclass mismatch for class Payment (TypeError)
  from /home/deepak/workspace/Project/app/models/spree/payment/processing_decorator.rb:1:in `<top (required)>'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/zeus-0.15.10/lib/zeus/load_tracking.rb:76:in `load'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/zeus-0.15.10/lib/zeus/load_tracking.rb:76:in `load'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/zeus-0.15.10/lib/zeus/load_tracking.rb:68:in `load'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `block in load'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:240:in `load_dependency'
  from /home/deepak/.rvm/gems/ruby-2.3.1/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `load'
  from /home/deepak/workspace/Project/config/application.rb:16:in `block (2 levels) in <class:Application>'
  from /home/deepak/workspace/Project/config/application.rb:15:in `glob'
  from /home/deepak/workspace/Project/config/application.rb:15:in `block in <class:Application>'

Solution

  • # /initializers/spree_overrides.rb
    module Spree
      class Payment < Spree::Base
        module Processing
          def purchase!
            started_processing!
            if source.class == Spree::PurchaseOrder
              gateway_action(source, :authorize, :pend)
            else
              gateway_action(source, :purchase, :complete)
            end
          end
        end
      end
    end
    

    Having it in initializer it will override the original method defined in Spree.