views:

129

answers:

2

I'm attempting to reopen the String class in rails and add a bunch more methods for my app to use. Writing the code isn't a problem - my question is rather about where this code should go.

It doesn't make sense to me to reopen a class inside a different model file, because it really has nothing to do with any of the models specifically. I thought perhaps somewhere in config or lib would make sense, but I'm not particularly well versed with RoR yet.

To summarize, where would be the most logical place to define class-modifying code, and are there any implications depending on where/when the code is loaded?

+3  A: 

I try keep these monkey-patches to a minimum, only when they are very clearly in the best interest of my code.

Lately I have preferred to keep the files organized in folders such as lib/monkey/string.rb, lib/monkey/hash.rb, etc. I then require all files in the lib/monkey folder in my environment.rb file.

# Load all monkey-patches.
Dir["lib/monkey/*.rb"].each {|monkeyfile| require monkeyfile}

This keeps all of my class modifying code isolated to one location, should a problem arise. I also enjoy the somewhat goofy naming, because it makes it stand out as something to be mindful of. Someone may have a better system, if so ... I'd love to hear about it!

Alex
Why wouldn't you use the initializers directory? It does what you're doing here.
ryeguy
I'll have to consider using the initializers, but it feels a little wrong to me to do something as big as modifying default classes in the initializers path.
Alex
What's the difference? You'd have to put your code in an environment file and it would be run when the framework boots anyways. The question here is whether you want to use something built into Rails, or whether you want to implement the exact same thing yourself. You can still create a directory called "monkey" initializers if you want. No need to reinvent the wheel.
ryeguy
I must say that while ryeguy's answer is simpler, I kind of see where you're coming too. Would like to hear some more opinions.
Jeriko
+9  A: 

The most logical place is probably in a file in the config/initializers directory. Any *.rb file you put in here will be automatically executed when rails boots. If you want, you could put them in a sub folder, so you could do something like config/initializers/extensions/*.rb.

ryeguy