Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set unit for number_to_currency with a user setting?

I want to allow users to change the currency unit throughout their account.

The obvious way to do it is to pass the unit parameter to number_to_currency, but given number_to_currency is used hundreds of times throughout the app, it seems a little repetitive to do that.

So is there some way to change what unit is used for all instances of number_to_currency based on a setting stored in the database for each user?

like image 809
Shpigford Avatar asked Dec 06 '22 03:12

Shpigford


2 Answers

Sounds to me like you need some sort of global function / variable to define the symbol

I would do it like this:

#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

This will allow you to call: <%= number_to_currency, unit: unit %>


Overriding Helper Method

number_to_currency is literally just a helper itself, which means you can append options on the fly:

Original

# 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

Amended

#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
like image 137
Richard Peck Avatar answered Dec 17 '22 05:12

Richard Peck


You could pass the currency as an option to the number_to_currency method as shown:

number_to_currency(1234567890.506, locale: :fr)

In that case you would need to replace :fr to whatever points to the user's setting and to create such a locale with such options:

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

Or you set the unit in another way:

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

Hope this helps you.

like image 29
danroux Avatar answered Dec 17 '22 04:12

danroux