在 Ruby on Rails 中,要扩展 String 类,代码应该放在哪里?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5654517/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Ruby on Rails, to extend the String class, where should the code be put in?
提问by nonopolarity
If on Ruby on Rails, I need to add a method called
如果在 Ruby on Rails 上,我需要添加一个名为
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.
想知道文件应该去哪里?(哪个目录和文件名,是否需要任何初始化代码?)这是一个 Rails 3.0.6 项目。
回答by Mike Lewis
I always add a core_extdirectory in my libdir.
我总是core_ext在我的目录中添加一个目录lib。
Create an initializerfor loading the custom extensions (for example: config/initializers/core_exts.rb). And add the following line in it:
创建用于加载自定义扩展的初始化程序(例如:)config/initializers/core_exts.rb。并在其中添加以下行:
Dir[File.join(Rails.root, "lib", "core_ext", "*.rb")].each {|l| require l }
and have your extension like:
并让您的扩展名如下:
lib/core_ext/string.rb
lib/core_ext/string.rb
class String
def capitalize_first
# ...
end
end
回答by njorden
You could do it in config/initializers/string.rb
你可以在 config/initializers/string.rb
class String
def capitalize_first
# ...
end
end
should be all you need (besides an app restart).
应该是您所需要的(除了应用程序重新启动)。
回答by Hopstream
The guidelines in Rails 3.1 is the way to go:
Rails 3.1 中的指导方针是要走的路:
http://guides.rubyonrails.org/plugins.html#extending-core-classes
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.
如果您遵循默认约定,则无需弄乱初始化程序配置。

