Posted 12 months ago. Visible to the public. Repeats.

Rails: How to use prepend to avoid monkey patches in modules

Let's say you have a gem which has the following module:

module SuperClient def 'Foo' end def bar 'Bar' end end

For reasons you need to override foo and bar.

Keep in mind: Your code quality is getting worse with with each prepend (other developers are not happy to find many library extensions). Try to avoid it if possible.

  1. Add a lib/ext/super_client.rb to your project (Folder or file needs to be required in an initializer)
  2. Add the extension, which overrides both methods (prepend is available since ruby >=2)
module SuperClientExtension def self.prepended(base) base.singleton_class.send(:prepend, ClassMethods) end module ClassMethods def foo 'New foo' end end def bar 'New bar' end end module SuperClient prepend SuperClientExtension end


class Test; include SuperClient; end => 'New foo' => 'New bar'
Growing Rails Applications in Practice
Check out our new e-book:
Learn to structure large Ruby on Rails codebases with the tools you already know and love.

Owner of this card:

Emanuel De
Last edit:
11 months ago
by Henning Koch
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more