Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using a lambda or proc and rails-money

I want to be able to set the currency on the model dynamically using the currency as set by the model's parent.

Like so:

class Event < ActiveRecord::Base
  belongs_to :edition
  monetize :price_cents, :with_currency => proc { |event| event.edition.currency }

event.edition.currency returns a symbol from the model's parent... e.g. :gbp

But it doesn't work. The default convention is:

monetize :bonus_cents, :with_currency => :gbp

Which works fine... any ideas?

https://github.com/RubyMoney/money-rails

like image 381
ere Avatar asked Jul 13 '13 09:07

ere


1 Answers

Try this:

class Event < ActiveRecord::Base
  belongs_to :edition
  monetize :price_cents

  def currency_for_price
    Money::Currency.find(edition.currency)
  end
end

I didn't test it thoroughly, but it seems to work.

2.0.0-p195 :012 > Event.new(
                      edition: Edition.new(currency: :gbp),
                      price: 123
                  ).price
 => #<Money fractional:12300 currency:GBP>
2.0.0-p195 :013 > Event.new(
                      edition: Edition.new(currency: :usd),
                      price: 456
                  ).price
 => #<Money fractional:45600 currency:USD>
like image 100
DNNX Avatar answered Sep 27 '22 23:09

DNNX