PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 26, 2022

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

 November 26, 2022     module, monkeypatching, ruby-on-rails, ruby-on-rails-6     No comments   

Issue

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



Answered By - stolarz
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing