加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 在类方法中使用包含的帮助程序的Rails

发布时间:2020-12-16 19:31:51 所属栏目:百科 来源:网络整理
导读:有人知道为什么包含的方法在类方法中不起作用? class MyClass include ActionView::Helpers::NumberHelper def test puts "Uploading #{number_to_human_size 123}" end def self.test puts "Uploading #{number_to_human_size 123}" endendree-1.8.7-2011.
有人知道为什么包含的方法在类方法中不起作用?
class MyClass
  include ActionView::Helpers::NumberHelper

  def test
    puts "Uploading #{number_to_human_size 123}"
  end

  def self.test
    puts "Uploading #{number_to_human_size 123}"
  end
end


ree-1.8.7-2011.03 :004 > MyClass.new.test
Uploading 123 Bytes
 => nil 
ree-1.8.7-2011.03 :005 > MyClass.test
NoMethodError: undefined method `number_to_human_size' for MyClass:Class
    from /path/to/my/code.rb:9:in `test'
    from (irb):5
ree-1.8.7-2011.03 :006 >

解决方法

对于想要在类级别lib或模型中使用某些自定义帮助程序的人来说,有时包含所有帮助程序是不值得的.而是直接调用它:
class MyClass
  def test
    ::ApplicationController.helpers.number_to_human_size(42)
  end
end

(摘自http://makandracards.com/makandra/1307-how-to-use-helper-methods-inside-a-model)

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读