Search code examples
ruby-on-railsrubyspree

Rails decorating controllers for spree


Simple ruby question I guess.

Why is this working?:

module Spree
  module Api
    module V1
      V1::TaxonsController.class_eval do
        def navigation
        end
      end
    end
  end
end

And when I do this:

module Spree
  module Api
    module V1
      TaxonsController.class_eval do
        def navigation
        end
      end
    end
  end
end

I get "UnknowAction", The action 'navigation' could not be found for Spree::Api::V1::TaxonsController

What I'm missing with the modules ?


Solution

  • V1::TaxonsController.class_eval do
      def navigation
      end
    end
    

    Creates the navigation instance method on the V1::TaxonsController class. When you omit V1 with Ruby's scope resolution operator (::), then the navigation instance method is not created on the V1::TaxonsController class, but on the TaxonsController class. I am guessing that the TaxonsController class is defined like this if it's a Rails controller:

    class V1::TaxonsController < ApplicationController
    end
    

    This would indicate that the above TaxonsController class is in a V1 directory in the Rails app (app/controllers/V1). So if you define an extra method on the TaxonsController class using class_eval like so:

    TaxonsController.class_eval do
      def navigation
      end
    end
    

    Then the navigation method would not be defined on TaxonsController in app/controllers/V1.

    I hope this helps.