aboutsummaryrefslogtreecommitdiffstats
path: root/activesupport/lib/active_support/number_helper/number_to_human_size.rb
blob: c0930564bc268dd0c58c1110a6ef087b0210003e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
require 'active_support/number_helper/number_converter'
require 'active_support/number_helper/number_to_rounded'

module ActiveSupport
  module NumberHelper
    class NumberToHumanSizeConverter < NumberConverter

      STORAGE_UNITS = [:byte, :kb, :mb, :gb, :tb]

      self.namespace        = :human
      self.need_valid_float = true

      def convert
        @number = Float(@number)

        # for backwards compatibility with those that didn't add strip_insignificant_zeros to their locale files
        unless options.key?(:strip_insignificant_zeros)
          options[:strip_insignificant_zeros] = true
        end

        if smaller_than_base?
          number_to_format = @number.to_i.to_s
        else
          human_size = @number / (base ** exponent)
          number_to_format = NumberToRoundedConverter.new(human_size, options).execute
        end
        conversion_format.gsub(/%n/, number_to_format).gsub(/%u/, unit)
      end

      private

        def conversion_format
          translate_number_value_with_default('human.storage_units.format', :locale => options[:locale], :raise => true)
        end

        def unit
          translate_number_value_with_default(storage_unit_key, :locale => options[:locale], :count => @number.to_i, :raise => true)
        end

        def storage_unit_key
          key_end = smaller_than_base? ? 'byte' : STORAGE_UNITS[exponent]
          "human.storage_units.units.#{key_end}"
        end

        def exponent
          max = STORAGE_UNITS.size - 1
          exp = (Math.log(@number) / Math.log(base)).to_i
          exp = max if exp > max # avoid overflow for the highest unit
          exp
        end

        def smaller_than_base?
          @number.to_i < base
        end

        def base
          opts[:prefix] == :si ? 1000 : 1024
        end

    end
  end
end