Posted 18 days 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:

Copy
module SuperClient def self.foo '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)
Copy
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

Test

Copy
class Test; include SuperClient; end SuperClient.foo => 'New foo' Test.new.bar => '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:

Avatar
Emanuel De
Last edit:
5 days 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