Ruby on Rails:为什么我的类扩展无法识别?

时间:2010-12-14 12:27:53

标签: ruby-on-rails ruby-on-rails-3

views/products/list.html.erb我使用:

<%= product.power.power_in_kw.to_kw if ... %>

to_kwlib/my_extensions.rb中与其他方法一起定义:

class Symbol
  def pluralize
    to_s.pluralize.to_sym
  end
end

class BigDecimal
  def to_kw
    number_to_currency(self, :unit => "kw", :format => "%n%u", :precision => 1)
  end
end

class Float
  def to_dollar
    number_to_currency(self)
  end
end

config/environment.rb最后有以下一行:

require 'my_extensions'

但是,我收到以下错误:

undefined method `to_kw' for #<BigDecimal:2704620,'0.555E2',8(8)>

我错过了什么?

2 个答案:

答案 0 :(得分:2)

我知道您提交此文件已经过了好几个小时,但重启应用后这些功能可能会有效。 lib中的项目通常不会像app中那样自动重新加载,因此在执行完全重启之前,所做的更改不会反映在应用程序中。

把它扔到那里:)

我还要指出,一旦你启动并运行这些方法,它们可能不会立即起作用。这是因为您的视图是在所有Rails视图助手的上下文中定义的,例如ActionView::Helpers::NumberHelper,它定义了number_to_currency。但是,lib中的扩展名未在此类上下文中定义,因此无法访问这些帮助程序。

ActionView::Helpers::NumberHelper.number_to_currency可能更有可能按预期工作。

答案 1 :(得分:1)

您应该在ActionView::Helpers::NumberHelperBigDecimal

中添加Float
class BigDecimal
  include ActionView::Helpers::NumberHelper
  def to_kw
    number_to_currency(self, :unit => "kw", :format => "%n%u", :precision => 1)
  end
end

class Float
  include ActionView::Helpers::NumberHelper
  def to_dollar
    number_to_currency(self)
  end
end

我认为错误undefined method to_kw是由未定义的方法number_to_currency引起的。

相关问题