Module: MoneyParser

Defined in:
lib/money_parser.rb

Defined Under Namespace

Classes: Engine

Class Method Summary collapse

Class Method Details

.parse(money_string) ⇒ Object



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
# File 'lib/money_parser.rb', line 13

def self.parse(money_string)

  return nil if money_string.nil?

  cleaned_up = money_string.
    gsub(/\s+/,'').
    gsub(/(\d)o/i){$1 + '0'}.
    gsub(/o(\d)/i){'0' + $1}.
    gsub(/\s+/,'').
    tr(',', '.').
    gsub(/[^\d\.-]/, '')

  return nil if cleaned_up.empty?

  chunks = cleaned_up.split('.')

  normalized = if chunks.size == 1
    cleaned_up
  else
    return nil if chunks[-1].nil?
    if chunks[-1].size > 2
      chunks.join
    else
      chunks[0..-2].join + '.' + chunks[-1]
    end
  end

  normalized ? BigDecimal.new(normalized) : normalized
end