Monkey Patching in Rails 3
Asked Answered
S

2

41

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.

Stereoisomerism answered 6/8, 2010 at 2:43 Comment(0)
Y
72

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.

Yuonneyup answered 6/8, 2010 at 3:34 Comment(1)
You can also organize them following this blog, makes for easier to debug and maintain monkey patches: justinweiss.com/blog/2015/01/20/…Stump
L
0

If it is class specific you could just re-define the method in the class you need it for. Otherwise, it totally depends on which part of the app you want to use your string method. As an example of opening a class to redefine a method: http://codepad.org/Cj1LHmQj but, you probably already knew you could do that.

Laquitalar answered 6/8, 2010 at 2:54 Comment(1)
If you want your string method available in many places, consider a module and put that in the lib directory, including where necessary.Laquitalar

© 2022 - 2024 — McMap. All rights reserved.