【问题标题】:Including modules and classes in rails在 rails 中包含模块和类
【发布时间】:2012-02-19 03:54:50
【问题描述】:

我很难在 /lib 的文件中包含一些视图助手,假设我有这个:

module TwitterPost
  include ActionView::Helpers::NumberHelper

  def update
    number_with_delimiter(1234567)
  end
end

我明白了:

NoMethodError: undefined method `number_with_delimiter' for TwitterPost:Module

但在我的控制台中,我可以只使用include ActionView::Helpers::NumberHelper,然后我可以只使用number_with_delimiter(1234567),它工作得很好。

这是为什么?我还需要在一堆不同的模型中包含ActionView::Helpers::NumberHelper,但我没有让它工作的运气。

【问题讨论】:

标签: ruby-on-rails ruby


【解决方案1】:

我认为您可能混淆了Modules 的工作方式。

您需要将模块混合到一个类中才能使实例方法起作用。

module TwitterPost
  include ActionView::Helpers::NumberHelper

  def update
    number_with_delimiter(1234567)
  end
end

class Foo
  include TwitterPost
end

foo = Foo.new
foo.update
   => "1,234,567" 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-08-14
    • 2021-12-25
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-27
    • 2018-07-05
    相关资源
    最近更新 更多