ruby-on-rails - 在 rails 中包含模块和类

标签 ruby-on-rails ruby

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

module TwitterPost
  include ActionView::Helpers::NumberHelper

  def update
    number_with_delimiter(1234567)
  end
end

我得到:

NoMethodError: undefined method `number_with_delimiter' for TwitterPost:Module

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

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

最佳答案

我认为您可能混淆了 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" 

关于ruby-on-rails - 在 rails 中包含模块和类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9011624/

相关文章:

ruby-on-rails - 我收到此错误 : NoMethodError at . .. 未定义的方法

ruby-on-rails - 如何在 Rails 3 的测试设置中设置 session 哈希?

ruby-on-rails - 使用 CarrierWave、Rails 3 上传种子文件

javascript - rake 数据库 :create - Could not find a JavaScript runtime

ruby-on-rails - before_destroy Rails admin ruby​​ 检查是否有依赖

ruby-on-rails - 如何在 Rails 4.0.3 中呈现关系的部分?

ruby-on-rails - 管理严重错误 : logging & email

ruby-on-rails - 在设计 Rails 数据库模式时如何避免使用关注点?

javascript - JavaScript 中的 Rails 哈希,访问值

ruby - Ruby 中 "puts {}.class"的意外行为