Patrick C
Patrick C

Reputation: 186

How to monkey-patch a class in Rails

I'm trying to monkey-patch the class "Tumble" with the module "Tinder". But when I add methods to the class, they aren't inherited. Constants, however, are.

lib/tumble.rb:

class Tumble
  ...

lib/tumble/tinder.rb

module Tinder
  APP_ID = 1234567890

  # Without self
  def xyz
    puts 'bar'
  end

config/initializers/tumble.rb

Tumble.include Tinder

The app loads Tumble and Tinder and I can access APP_ID:

$ rails r 'puts Tumble::APP_ID'
1234567890

But Tumble didn't inherit the methods:

[~/tinder]$ rails r 'puts Tumble.foo'
Please specify a valid ruby command or the path of a script to run.
Run 'bin/rails runner -h' for help.

undefined method `foo' for Tumble:Class
[~/tinder]$ rails r 'puts Tumble.xyz'
Please specify a valid ruby command or the path of a script to run.
Run 'bin/rails runner -h' for help.

undefined method `xyz' for Tumble:Class

How do I patch Tumble to include these methods from Tinder?

Thanks :)

Upvotes: 1

Views: 2709

Answers (2)

JollyProgrammer
JollyProgrammer

Reputation: 186

class Tinder
 def initialize
  # some code here
 end
end

Imagine that this above was the class that you wanted to monkey-patch. To monkey-patch it you only need to write (on any place that gets loaded) the class Tinder again with the code to be added like this:

class Tinder
 def some_more_code
  # does great stuff
 end
end

This is monkey-patch. Modules won't do monkey-patch. They extend functionality but in a different way.

Just be aware not to override any methods of the original class that you want to monkey-patch, unless, of course, if that is your goal.

Upvotes: 0

max pleaner
max pleaner

Reputation: 26758

When you call Tumble.foo that's calling foo as if it were a class method.

Yet when you do Tumble.include Tinder that adds the module's instance methods as instance methods of Tumble.

So, your current code should work if you do Tumble.new.foo.

You can also make Tumble.foo work with Tumble.extend Tinder.

Upvotes: 2

Related Questions