[ACCEPTED]-In Ruby on Rails, to extend the String class, where should the code be put in?-ruby-on-rails-3

Accepted answer
Score: 144

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
Score: 66

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).

Score: 7

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.

More Related questions