Ruby on Rails | Screencasts | Download | Documentation | Weblog | Community | Source

Ticket #11149: format_option_for_number_to_currency.diff

File format_option_for_number_to_currency.diff, 2.7 kB (added by lylo, 5 months ago)
  • actionpack/test/template/number_helper_test.rb

    old new  
    2525    assert_equal("$1,234,567,890.5", number_to_currency(1234567890.50, {:precision => 1})) 
    2626    assert_equal("£1234567890,50", number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""})) 
    2727    assert_equal("$1,234,567,890.50", number_to_currency("1234567890.50")) 
     28    assert_equal("1,234,567,890.50 Kč", number_to_currency("1234567890.50", {:unit => "Kč", :format => "%n %u"})) 
    2829    assert_equal("$x.", number_to_currency("x")) 
    2930    assert_nil number_to_currency(nil) 
    3031  end 
  • actionpack/lib/action_view/helpers/number_helper.rb

    old new  
    5454      # * <tt>:unit</tt>  - Sets the denomination of the currency (defaults to "$"). 
    5555      # * <tt>:separator</tt>  - Sets the separator between the units (defaults to "."). 
    5656      # * <tt>:delimiter</tt>  - Sets the thousands delimiter (defaults to ","). 
     57      # * <tt>:format</tt>  - Sets the format of the output string (defaults to "%u%n"). The field types are: 
    5758      # 
     59      #     %u  The currency unit 
     60      #     %n  The number 
     61      # 
    5862      # ==== Examples 
    5963      #  number_to_currency(1234567890.50)                    # => $1,234,567,890.50 
    6064      #  number_to_currency(1234567890.506)                   # => $1,234,567,890.51 
     
    6266      # 
    6367      #  number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "") 
    6468      #  # => &pound;1234567890,50 
     69      #  number_to_currency(1234567890.50, :unit => "&pound;", :separator => ",", :delimiter => "", :format => "%n %u") 
     70      #  # => 1234567890,50 &pound; 
    6571      def number_to_currency(number, options = {}) 
    6672        options   = options.stringify_keys 
    6773        precision = options["precision"] || 2 
    6874        unit      = options["unit"] || "$" 
    6975        separator = precision > 0 ? options["separator"] || "." : "" 
    7076        delimiter = options["delimiter"] || "," 
     77        format    = options["format"] || "%u%n" 
    7178 
    7279        begin 
    7380          parts = number_with_precision(number, precision).split('.') 
    74           unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 
     81          format.gsub(/%n/, number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s).gsub(/%u/, unit) 
    7582        rescue 
    7683          number 
    7784        end