开发者

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 开发者_如何学Goany initialize code needed?) This is for a Rails 3.0.6 project.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜