有人知道为什么包含的方法在类方法中不起作用?
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)