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

Ticket #6351: to_currency_helper_with_order.patch

File to_currency_helper_with_order.patch, 2.5 kB (added by jesperronn, 2 years ago)
  • actionpack/lib/action_view/helpers/number_helper.rb

    old new  
    3434      #    number_to_currency(1234567890.506)    => $1,234,567,890.51 
    3535      #    number_to_currency(1234567890.50, {:unit => "£", :separator => ",", :delimiter => ""}) => £1234567890,50 
    3636      def number_to_currency(number, options = {}) 
     37        options[:order] ||= [:unit, :number] 
    3738        options = options.stringify_keys 
    3839        precision, unit, separator, delimiter = options.delete("precision") { 2 }, options.delete("unit") { "$" }, options.delete("separator") { "." }, options.delete("delimiter") { "," } 
    3940        separator = "" unless precision > 0 
     41 
     42        #add leading space before trailing unit 
     43        unit = " " + unit if options[:order] == [:number, :unit] 
     44        output = '' 
    4045        begin 
    41           parts = number_with_precision(number, precision).split('.') 
    42           unit + number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 
     46          options["order"].each do |param| 
     47                case param 
     48                  when :unit 
     49                    output << unit 
     50                  when :number 
     51                parts = number_with_precision(number, precision).split('.') 
     52                output << number_with_delimiter(parts[0], delimiter) + separator + parts[1].to_s 
     53            end 
     54          end 
    4355        rescue 
    44           number 
     56          output = number 
    4557        end 
     58        output 
    4659      end 
    4760 
    4861      # Formats a +number+ as into a percentage string. The +options+ hash can be used to customize the format of the output. 
     
    7689      end 
    7790 
    7891      # Returns a formatted-for-humans file size. 
    79       #  
     92      # 
    8093      # Examples: 
    8194      #   human_size(123)          => 123 Bytes 
    8295      #   human_size(1234)         => 1.2 KB 
     
    8497      #   human_size(1234567)      => 1.2 MB 
    8598      #   human_size(1234567890)   => 1.1 GB 
    8699      def number_to_human_size(size) 
    87         case  
     100        case 
    88101          when size == 1        : '1 Byte' 
    89102          when size < 1.kilobyte: '%d Bytes' % size 
    90103          when size < 1.megabyte: '%.1f KB'  % (size / 1.0.kilobyte) 
     
    95108      rescue 
    96109        nil 
    97110      end 
    98        
     111 
    99112      alias_method :human_size, :number_to_human_size # deprecated alias 
    100113 
    101114      # Formats a +number+ with a level of +precision+.