Search code examples
ruby-on-railsrubyactivesupport-concern

How to override method from mixin?


I'm working in some ruby code. There's a module like the below:

module ResourceTransformation
  extend ActiveSupport::Concern

  class_methods do
    def import(resource)
    end
  end
end

In one of the classes that uses this module, I would like to override the import method. My current code looks like this:

class SomeEntity < ApplicationRecord
  include ResourceTransformation

  def import(resource)
    puts "in overriden import method!!!"
    # super
  end
end

Unfortunately, when I call SomeEntity.import it is simply invoking and returning the results from the module import method rather than from the class import method...

How can I properly override the module method with my class method?


Solution

  • class_methods in your concern define class methods from given block

    That's why you need override not instance but class (self) method

    class SomeEntity < ApplicationRecord
      include ResourceTransformation
    
      def self.import(resource)
        puts "in overriden import method!!!"
      end
    end