在rails中,放置需要在任何地方可用的方法的正确位置 [英] in rails, where is right place to put methods that need to be available 'anywhere'
问题描述
我有很多实用工具方法(例如用于重新格式化或解析诸如字符串之类的简单对象的方法).
I have lots of little utility methods (such as for reformatting or parsing simple objects like strings) I have been putting in ApplicationHelper.
但是,显然模型中的类方法无法访问ApplicationHelper方法.
However, ApplicationHelper methods apparently cannot be accessed by class methods in a model.
有一个解决方法,可以在我的整个项目中使用:
There is a workaround, which is to sprinkle thoughout my project:
include ApplicationHelper # needed to use apphelper method in instance method
extend ApplicationHelper # needed to use apphelper method in class method
,它似乎有效.但这似乎是一种矛盾.
and it seems to work. But it seems like a kludge.
是否有放置实用程序方法的更好的地方,以便可以从我的项目中的任何位置访问它们-视图,控制器方法,模型实例方法,模型类方法?
Is there a better place to put utility methods so they can be accessed from anywhere in my project - view, controller method, model instance metho, model class method?
推荐答案
这是lib/
的用途.我在lib/deefour.rb
中有一个文件,
This is what lib/
is for. I have a file at lib/deefour.rb
with
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
中,请确保您拥有
In your config/application.rb
make sure you have
config.autoload_paths += Dir["#{config.root}/lib"]
最后,在ApplicationController
(对于控制器),ApplicationHelper
(对于视图)中,以及我需要的其他地方(即特定我只是做
Finally, in ApplicationController
(for controllers), ApplicationHelper
(for views), and wherever else I need it (ie. a specific model here and there) I simply do
include ::Deefour::Helpers
这篇关于在rails中,放置需要在任何地方可用的方法的正确位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!