money
taxiing out. He knows just what he needs:
# 5 dollars = Money.new(500, 'USD') # 10 ! euros = Money.new(1000, 'EUR') # # euros > dollars # => true # euros.exchange_to('USD') # => #<Money cents:1408 currency:USD> # !!11 Money.new(1000, 'USD') + Money.new(1000, 'EUR') # => #<Money cents:2408 currency:USD>
# Gemfile gem 'money' gem 'google_currency', :require => 'money/bank/google_currency' # cartoon.rb class Cartoon < ActiveRecord::Base composed_of :price, :class_name => 'Money', :mapping => [[ 'price_in_cents', 'cents' ], [ '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") } end # migration create_table :cartoons do |t| # ... t.integer :price_in_cents, :default => 0, :null => false t.string :price_currency, :limit => 3, :null => false # ... end
# intializers/money.rb Money.default_bank = Money::Bank::GoogleCurrency.new
# Gemfile gem 'counterfeit' # cartoon.rb class Cartoon < ActiveRecord::Base has_counterfeit :price # # :currency => 'RUB' # , . # :currency_attribute => :price_currency, # :amount_attribute => :price_in_cents end # migration create_table :cartoons do |t| # ... t.money :price # ... end
class Cartoon < ActiveRecord::Base has_money :price # , ? end
Source: https://habr.com/ru/post/122022/