Read more

Call original method when monkey patching

Jakob Scholz
January 08, 2021Software engineer at makandra GmbH

Ruby offers monkey patching methods in order to change the behavior of a library if there's no better way.

Illustration online protection

Rails Long Term Support

Rails LTS provides security patches for old versions of Ruby on Rails (2.3, 3.2, 4.2 and 5.2)

  • Prevents you from data breaches and liability risks
  • Upgrade at your own pace
  • Works with modern Rubies
Read more Show archive.org snapshot

We can call the method we're overriding inside our monkey patch:

class Foo
  def bar(argument)
    'Hello' + argument
  end
end 

module FooExtensions
  def bar
    super(' in my') + ' World'
  end
end

class Foo
  prepend FooExtensions # the only change to above: prepend instead of include
end

Foo.new.bar # => 'Hello in my World'

As mentioned, monkey patches are usually a threat to your code quality, so try to avoid them if possible.

Further readings

For a better understanding have a look at this article Show archive.org snapshot .

Posted by Jakob Scholz to makandra dev (2021-01-08 08:12)