What is the preferred way to Monkey Patch in Rails 3?
I just want to add a method to the String class. I'm more looking at where to place the file.
In Ruby, a Monkey Patch (MP) is referred to as a dynamic modification to a class and by a dynamic modification to a class means to add new or overwrite existing methods at runtime. This ability is provided by ruby to give more flexibility to the coders.
Monkey patching is good for testing or mocking out behavior. They can be localized in factory/class decorators/metaclasses where they create a patched new class/object from another object to help with "cross-cutting concerns" in between ALL methods like logging/memoization/caching/database/persistance/unit conversion.
Monkey patching can only be done in dynamic languages, of which python is a good example. Changing a method at runtime instead of updating the object definition is one example;similarly, adding attributes (whether methods or variables) at runtime is considered monkey patching.
A monkey patch is a way for a program to extend or modify supporting system software locally (affecting only the running instance of the program).
The initializer directory is a good place to collect all those little scraps. Since I tend to go a bit overboard with core extensions, I like to make a folder there called "extensions" and toss them all in there.
So, try /config/initializers/string_extension.rb
, or /config/initializers/extensions/string.rb
, or something similar. Either way, you can just forget about them afterward - Rails will require them for you, so you don't need to do it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With