Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Monkey Patching in Rails 3

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.

like image 447
Dex Avatar asked Aug 06 '10 02:08

Dex


People also ask

What is monkey patching in Ruby?

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.

Is monkey patching a good idea?

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.

What is monkey patching give example?

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.

What does monkey patching do?

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).


1 Answers

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.

like image 138
PreciousBodilyFluids Avatar answered Sep 29 '22 04:09

PreciousBodilyFluids