Class: ActiveRecord::ConnectionAdapters::PostgreSQLAdapter::OID::Money

Inherits:
Type
  • Object
show all
Defined in:
activerecord/lib/active_record/connection_adapters/postgresql/oid.rb

Instance Method Summary collapse

Methods inherited from Type

#type

Instance Method Details

#type_cast(value) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'activerecord/lib/active_record/connection_adapters/postgresql/oid.rb', line 35

def type_cast(value)
  return if value.nil?
  return value unless String === value

  # Because money output is formatted according to the locale, there are two
  # cases to consider (note the decimal separators):
  #  (1) $12,345,678.12
  #  (2) $12.345.678,12
  # Negative values are represented as follows:
  #  (3) -$2.55
  #  (4) ($2.55)

  value.sub!(/^\((.+)\)$/, '-\1') # (4)
  case value
  when /^-?\D+[\d,]+\.\d{2}$/  # (1)
    value.gsub!(/[^-\d.]/, '')
  when /^-?\D+[\d.]+,\d{2}$/  # (2)
    value.gsub!(/[^-\d,]/, '').sub!(/,/, '.')
  end

  ConnectionAdapters::Column.value_to_decimal value
end