Shp*_*ord 3 currency ruby-on-rails ruby-on-rails-4
我想允许用户在整个帐户中更改货币单位.
显而易见的方法是将unit参数传递给number_to_currency,但是number_to_currency在整个应用程序中使用了数百次,这似乎有点重复.
那么是否有一些方法可以number_to_currency根据每个用户的数据库中存储的设置更改所有实例的使用单位?
听起来像你需要某种全局函数/变量来定义符号
我会这样做:
#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
Run Code Online (Sandbox Code Playgroud)
这将允许您致电: <%= number_to_currency, unit: unit %>
重写助手方法
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
Run Code Online (Sandbox Code Playgroud)
修订
#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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
995 次 |
| 最近记录: |