Skip to content

Ruby on Rails (Money.gem 3.0.3 and later)

elmatou edited this page Jan 18, 2011 · 14 revisions

Use the #composed_of helper to let Active Record deal with embedding the money object in your models. The following example requires a cents and a currency field.

composed_of :price,
  :class_name => "Money",
  :mapping => [%w(cents cents), %w(currency currency_as_string)],
  :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) },
  :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }

Adding a converter Proc to the #composed_of allow any string (eg : textfield) to be saved in the model through Money.parse (or String.to_money) if you have a second field with the currency, it will use it to create the Money object.

Clone this wiki locally