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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
|
# File 'lib/mongoid_money_field.rb', line 12
def money_field_with_options(columns, opts = {})
[columns].flatten.each do |name|
opts = {fixed_currency: nil, default: nil}.merge(opts)
if opts[:default].nil?
default = nil
default_currency = ::Money.default_currency.iso_code if opts[:fixed_currency].nil?
else
default_money = Money.parse(opts[:default])
default = default_money.cents
default_currency = default_money.currency.iso_code if opts[:fixed_currency].nil?
end
attr_cents = (name.to_s + '_cents').to_sym
field attr_cents, type: Integer, default: default
if opts[:fixed_currency].nil?
attr_currency = (name.to_s + '_currency').to_sym
field attr_currency, type: String, default: default_currency
end
define_method(name) do
cents = read_attribute(attr_cents)
if opts[:fixed_currency].nil?
currency = read_attribute(attr_currency)
else
currency = opts[:fixed_currency]
end
if cents.nil?
nil
else
Money.new(cents, currency || ::Money.default_currency)
end
end
define_method("#{name}=") do |value|
if value.blank?
write_attribute(attr_cents, nil)
if opts[:fixed_currency].nil?
write_attribute(attr_currency, nil)
end
nil
else
money = value.to_money
write_attribute(attr_cents, money.cents)
if opts[:fixed_currency].nil?
write_attribute(attr_currency, money.currency.iso_code)
end
money
end
end
end
end
|