nonopolarity
nonopolarity

Reputation: 151006

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

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.

Upvotes: 83

Views: 34938

Answers (3)

Mike Lewis
Mike Lewis

Reputation: 64147

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

Upvotes: 148

Hopstream
Hopstream

Reputation: 6451

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.

Upvotes: 7

njorden
njorden

Reputation: 2606

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

Upvotes: 66

Related Questions