在rails中,哪里是放置需要“随处”可用的方法的正确位置

我有很多小实用工具方法(例如重新格式化或解析像字符串这样的简单对象)我一直在使用ApplicationHelper。

但是,ApplicationHelper方法显然无法通过模型中的类方法访问。

有一个解决方法,即在我的项目中撒上:

include ApplicationHelper # needed to use apphelper method in instance method extend ApplicationHelper # needed to use apphelper method in class method 

它似乎工作。 但它似乎是一个kludge。

是否有更好的地方放置实用程序方法,以便可以从我的项目中的任何位置访问它们 – 视图,控制器方法,模型实例方法,模型类方法?

这就是lib/的用途。 我在lib/deefour.rb上有一个文件

 require "deefour/core_ext" module Deefour; end 

我把自定义方法放在lib/deefour/helpers.rb

 module Deefour module Helpers extend self def some_method # ... end end end 

lib/deefour/core_ext.rb核心猴子补丁

 class String def my_custom_string_method(str) # ... end end 

config/initializers/deefour.rb我放了

 require "deefour" 

在你的config/application.rb确保你有

 config.autoload_paths += Dir["#{config.root}/lib"] 

最后,在ApplicationController (用于控制器)ApplicationHelper (用于视图) ,以及我需要的任何其他地方(即,这里和那里的特定模型)我只是做

 include ::Deefour::Helpers