Module: Monies::Digits

Defined in:
lib/monies/digits.rb

Class Method Summary collapse

Class Method Details

.dump(instance, scale: nil, zero: '0', separator: '.', thousands_separator: nil) ⇒ Object



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
# File 'lib/monies/digits.rb', line 4

def self.dump(instance, scale: nil, zero: '0', separator: '.', thousands_separator: nil)
  return zero if instance.zero?

  string = instance.value.abs.to_s

  integral_length = string.length - instance.scale

  unless thousands_separator.nil?
    index = integral_length
    while index > 3
      index -= 3
      string.insert(index, thousands_separator)
      integral_length += thousands_separator.length
    end
  end

  unless instance.scale.zero? && scale.nil? || scale == 0
    if integral_length > 0
      string.insert(integral_length, separator)
    else
      string = string.rjust(instance.scale, '0') if integral_length < 0
      string.insert(0, separator)
      string.insert(0, '0')
    end
  end

  unless scale.nil?
    if scale > instance.scale
      string = string.ljust(string.length + scale - instance.scale, '0')
    elsif scale < instance.scale
      string.slice!(scale - instance.scale .. -1)
    end
  end

  string.insert(0, '-') if instance.negative?
  string
end

.load(string, currency) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/monies/digits.rb', line 42

def self.load(string, currency)
  integral_digits, fractional_digits = string.split('.')

  value = integral_digits.to_i

  if fractional_digits.nil?
    scale = 0
  else
    scale = fractional_digits.length

    value *= Monies::BASE ** scale

    if string.start_with?('-')
      value -= fractional_digits.to_i
    else
      value += fractional_digits.to_i
    end
  end

  Monies.new(value, scale, currency)
end