0

I’m using Ruby on Rails 6.1.4.4. I want to override a method in a gem, whose signature is this

module Juixe
  module Acts
    module Commentable
      module ClassMethods
        def acts_as_commentable(*args)
        …
       end
      end
    end
  end
end

So I tried creating a file, lib/ext/acts_as_commentable_extensions.rb, and including this code

require 'acts_as_commentable'

module GemExtensions
  module Commentable
    def hello
      print "hello\n"
    end

    def acts_as_commentable(*args)
      abcdef
    end
  end
end

module Juixe
  module Acts
    module Commentable
      module ClassMethods
        include GemExtensions::Commentable
      end
    end
  end
end

Juixe::Acts::Commentable::ClassMethods.instance_method(:hello).source.display
Juixe::Acts::Commentable::ClassMethods.instance_method(:acts_as_commentable).source.display

Although the first statement prints out the correct source code from my new method “hello,” the second prints out the old source code from the original gem as opposed to my new code. How do I override this method with my own code?

1 Answer 1

0

Try prepend GemExtensions::Commentable instead of include, it will make Ruby to search for the method first in prepended module. More explanation here https://medium.com/@leo_hetsch/ruby-modules-include-vs-prepend-vs-extend-f09837a5b073

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.