在 Ruby on Rails 中,要扩展 String 类,代码应该放在哪里? [英] In Ruby on Rails, to extend the String class, where should the code be put in?
本文介绍了在 Ruby on Rails 中,要扩展 String 类,代码应该放在哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果在 Ruby on Rails 上,我需要添加一个名为
If on Ruby on Rails, I need to add a method called
class String
def capitalize_first
# ...
end
end
想知道文件应该去哪里?(哪个目录和文件名,是否需要任何初始化代码?)这是针对 Rails 3.0.6 项目的.
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.
推荐答案
我总是在我的 lib
目录中添加一个 core_ext
目录.
I always add a core_ext
directory in my lib
dir.
创建一个 initializer 以加载自定义扩展(例如:config/initializers/core_exts.rb
).并在其中添加以下行:
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 }
并让您的扩展程序像:
lib/core_ext/string.rb
class String
def capitalize_first
# ...
end
end
这篇关于在 Ruby on Rails 中,要扩展 String 类,代码应该放在哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文