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

匿名 (未验证) 提交于 2019-12-03 02:00:02

问题:

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.

回答1:

I always add a core_ext directory in my lib dir.

Create and 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 


回答2:

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



回答3:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!