可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
If on Ruby on Rails, I need to add a method called
class String def capitalize_first # ... end end
and wonder where should the file go to? (which directory and filename, and is any initialize code needed?) This is for a Rails 3.0.6 project.
回答1:
I always add a core_ext
directory in my lib
dir.
Create and initializer for loading the custom extensions (for example: config/initializers/core_exts.rb
). And add the following line in it:
Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each {|l| require l }
and have your extension like:
lib/core_ext/string.rb
class String def capitalize_first # ... end end
回答2:
You could do it in config/initializers/string.rb
class String def capitalize_first # ... end end
should be all you need (besides an app restart).
回答3:
The guidelines in Rails 3.1 is the way to go:
http://guides.rubyonrails.org/plugins.html#extending-core-classes
If you follow the default convention you won't need to mess with an initializer config.