Search code examples
ruby-on-railsmoduleruby-on-rails-6monkeypatching

Why is "include" not using my monkey-pathced method for my module?


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?


Solution

  • 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