In Ruby on Rails, to extend the String class, where should the code be put in?

Ruby on-RailsRubyRuby on-Rails-3

Ruby on-Rails Problem Overview


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.

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

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

Solution 2 - Ruby on-Rails

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

Solution 3 - Ruby on-Rails

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionnonopolarityView Question on Stackoverflow
Solution 1 - Ruby on-RailsMike LewisView Answer on Stackoverflow
Solution 2 - Ruby on-RailsnjordenView Answer on Stackoverflow
Solution 3 - Ruby on-RailsHopstreamView Answer on Stackoverflow