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

前端之家收集整理的这篇文章主要介绍了ruby-on-rails – 在类方法中使用包含的帮助程序的Rails前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
@H_301_1@有人知道为什么包含的方法在类方法中不起作用?
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)

原文链接:https://www.f2er.com/ruby/271265.html

猜你在找的Ruby相关文章