In Ruby on Rails, to extend the String class, where should the code be put in?
I always add a core_ext
directory in my lib
dir.
Create an 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
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).
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.