【问题标题】:in rails, where is right place to put methods that need to be available 'anywhere'在 Rails 中,哪里是放置需要“随处”可用的方法的正确位置
【发布时间】:2012-12-15 01:16:44
【问题描述】:

我有很多小实用方法(例如用于重新格式化或解析字符串等简单对象)我一直在 ApplicationHelper 中。

但是,ApplicationHelper 方法显然不能被模型中的类方法访问。

有一个解决方法,那就是在我的项目中洒水:

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

而且它似乎有效。但这似乎是一个杂物。

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

【问题讨论】:

  • 你在猴子补丁中像 String 这样的核心类吗?还是这些特定领域的变化? (例如格式化地址)只是想了解这些方法是否真的是“无处不在”的方法,或者真的只是与模型相关但希望在任何地方都可以访问。是否可以看到一些示例方法?这可能有助于引导对话。
  • 例如,我们经常处理电话号码,并且有很多方法可以根据一些自定义要求对其进行清理

标签: ruby-on-rails helper


【解决方案1】:

这就是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

【讨论】:

  • 一件事——在你的 config/initializers/deefour.rb 示例中,我认为它需要是“包含”而不是“要求”
  • 不,绝对不是。我建议阅读 Ruby 中 requireinclude 之间的区别。在这种情况下,我试图将特定模块(它的类/方法)的内容包含到应用程序范围中 --- 我正在尝试加载 文件,使模块本身可在应用程序的其他文件中使用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2010-10-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-22
  • 1970-01-01
相关资源
最近更新 更多