在Rails中干燥视图(number_to_currency)

Gav*_*Gav 11 views ruby-on-rails dry

我的代码类似于:

number_to_currency(line_item.price, :unit => "£")

在各种模型中乱丢我的观点.由于只有在英镑(£)我的应用程序处理,我不应该提出这个到我的每一个模型,以便line_item.price返回,因为它应该是字符串(即number_to_currency(line_item.price, :unit => "£")line_item.price是一样的,我想,这样做我应该:

def price
 number_to_currency(self.price, :unit => "£")
end
Run Code Online (Sandbox Code Playgroud)

但这不起作用.如果price在模型中已经定义,那么Rails的报告"堆栈级别太深",当我改变def pricedef amount,然后抱怨说number_to_currency没有定义?

Jos*_*osh 41

如果要更改整个应用程序的默认值,可以编辑config/locales/en.yml

我看起来像这样:

# Sample localization file for English. Add more files in this directory for other locales.
# See http://github.com/svenfuchs/rails-i18n/tree/master/rails%2Flocale for starting points.
"en":
  number:
    currency:
        format:
            format: "%u%n"
            unit: "£"
            # These three are to override number.format and are optional
            separator: "."
            delimiter: ","
            precision: 2
Run Code Online (Sandbox Code Playgroud)

除了单位之外的所有东西都是可选的,并且会回归到默认值,但我把它放进去,所以我知道我可以改变什么值.你也可以使用£符号而不是£.

  • 我总是使用自定义助手,类似于Larry K接受的答案所描述的,但这更清洁了. (2认同)

Lar*_*y K 13

number_to_currency是一个视图助手,因此在模型中不可用.

您可以通过在application_helper.rb中定义自己的帮助程序来保存一些关键笔划(因此它可供所有视图使用).例如

def quid(price)
  number_to_currency(price, :unit => "£")
end
Run Code Online (Sandbox Code Playgroud)

然后在视图中调用它:

quid(line_item.price)
Run Code Online (Sandbox Code Playgroud)


mik*_*kej 6

堆栈级别太深错误的原因是,当您self.priceprice方法中说您正在创建对价格方法的无限递归调用时,因为您现在已经覆盖了正常的访问器方法.为避免这种情况,您需要使用属性哈希来访问price字段的值.例如:

def price
 number_to_currency(attributes['price'], :unit => "£")
end
Run Code Online (Sandbox Code Playgroud)

除了number_to_currencyLarry K所描述的模型代码中没有的事实.