Module: Numerals::Format::Output

Included in:
Numerals::Format
Defined in:
lib/numerals/format/output.rb

Overview

Formatted output implementation

Instance Method Summary collapse

Instance Method Details

#write(number, options = {}) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/numerals/format/output.rb', line 8

def write(number, options={})
  # 1. Convert number to numeral
  numeral = conversion_out(number)
  if numeral.approximate? && !@rounding.free?
    insignificant_digits = @rounding.precision(numeral) - numeral.digits.size
    if insignificant_digits > 0
      numeral.expand! @rounding.precision(numeral)
    end
  end
  return numeral if options[:output] == :numeral
  # 2. Break numeral into parts (digits, etc.)
  num_parts = partition_out(numeral, insignificant_digits: insignificant_digits)
  if !@symbols.repeating && num_parts.repeating?
    raise Format::InvalidRepeatingNumeral, "Invalid format: cannot represent exact value"
  end
  # 3. Represent parts as text
  text_parts = symbolize_out(num_parts)
  # 4. Assemble text parts into output notation
  output = options[:output] || StringIO.new
  assemble_out(output, text_parts)
  options[:output] ? output : output.string
end