Class: ReeNumber::NumberToHumanSize

Inherits:
Object
  • Object
show all
Includes:
Ree::FnDSL
Defined in:
lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_human_size.rb

Constant Summary collapse

DEFAULTS =
{
  locale: :en,
  format: "%n %u",
  precision: 3,
  significant: true,
  strip_insignificant_zeros: true,
  separator: ".",
  delimiter: "",
  round_mode: :default
}.freeze
BASE =
1024

Instance Method Summary collapse

Instance Method Details

#call(number, **opts) ⇒ Object



110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
# File 'lib/ree_lib/packages/ree_number/package/ree_number/functions/number_to_human_size.rb', line 110

def call(number, **opts)
  options = DEFAULTS.merge(opts)

  number = Float(number)

  if smaller_than_base?(number)
    number_to_format = number.to_i.to_s
  else
    human_size = number / (BASE**exponent(number))
    number_to_format = number_to_rounded(
      human_size,
      **slice(
        options,
        [:precision, :significant, :strip_insignificant_zeros, :round_mode]
      )
    )
  end

  storage_unit_key = storage_unit_key(number)

  unit = unit(options[:locale], storage_unit_key, number)
  result_number = options[:format]
    .gsub("%n", number_to_format)
    .gsub("%u", unit)

  number_to_delimited(
    result_number,
    **slice(options, [:separator, :delimiter])
  )
end