[ACCEPTED]-In Ruby on Rails, to extend the String class, where should the code be put in?-ruby-on-rails-3
Accepted answer
I always add a core_ext
directory in my lib
dir.
Create 3 an initializer for loading the custom extensions (for 2 example: config/initializers/core_exts.rb
). And add the following line in 1 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 1 be all you need (besides an app restart).
The guidelines in Rails 3.1 is the way to 3 go:
http://guides.rubyonrails.org/plugins.html#extending-core-classes
If you follow the default convention 2 you won't need to mess with an initializer 1 config.
Source:
stackoverflow.com
More Related questions
Cookie Warning
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.