开发者

Where to reopen a class in RoR

I'm attempting to 开发者_StackOverflowreopen 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?


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.


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜