2014-01-16 56 views
2

我想允许用户在整个账户中更改货币单位。用户设置为number_to_currency设置单位?

明显的做法是将unit参数传递给number_to_currency,但是由于number_to_currency在整个应用程序中使用了数百次,似乎有点重复这样做。

所以是有一些方法来改变基于存储在数据库中为每个用户设置使用什么单位的number_to_currency所有实例?

+0

你只是需要更改货币符号,或过于转换? –

回答

8

听起来像你对我需要某种形式的全局函数/变量定义符号

我会做这样的:

#app/helpers/application_helper.rb 
def unit 
    User.find(current_user.id).select(:currency_type) #I don't know how your units are stored - you may need logic to return the correctly formatted unit 
end 

这将允许您拨打:<%= number_to_currency, unit: unit %>


重载helper方法

number_to_currency是真的只是一个辅助本身,这意味着你可以附加在飞行选项:

原始

# File actionpack/lib/action_view/helpers/number_helper.rb, line 106 
     def number_to_currency(number, options = {}) 
     return unless number 
     options = escape_unsafe_delimiters_and_separators(options.symbolize_keys) 

     wrap_with_output_safety_handling(number, options.delete(:raise)) { 
      ActiveSupport::NumberHelper.number_to_currency(number, options) 
     } 
     end 

修订

#app/helpers/application_herlper.rb 
    def number_to_currency(number, options ={}) 
     unit = User.find(current_user.id).select(:currency_type) 
     options[:unit] = unit unless options[:unit].present? 
     super 
    end 
+0

是的,就像我刚才提到的那样,这是我希望避免的......设置'unit'参数曾经一次使用'number_to_currency'。 – Shpigford

+0

更新应答 –

+0

更新为你解答 –

3

你可以通过货币作为一个选项number_to_currency方法如图所示:

number_to_currency(1234567890.506, locale: :fr) 

在这种情况下,你将需要更换:fr到任何点到用户的设置,并与这些选项创建一个这样的区域:

number: 
    currency: 
    format: 
     unit: '€' 
     format: '%n %u' 
     separator: "," 
     delimiter: "." 
     precision: 2 
     significant: false 
     strip_insignificant_zeros: false 

或者你设置的单位以另一种方式:

number_to_currency(1234567890.50, unit: "&pound;", format: "%u %n") 
=> "&pound; 1.234.567.890,50" 

希望这可以帮助你。