Sha256: e9f5fa9e3bc2c815af3ac828ef09a1ed3e323dd0565216af37338d2e0223d0db
Contents?: true
Size: 1.92 KB
Versions: 9
Compression:
Stored size: 1.92 KB
Contents
# frozen_string_literal: true require "money" Money.rounding_mode = BigDecimal::ROUND_HALF_UP # Creates accessors for money values module Sequel::Plugins::MoneyAccessors MoneyClassRequired = Class.new(StandardError) module ClassMethods # Setup money accessor # # @param amount_column [Symbol] amount column # @param currency_column [Symbol] currency column # @example # class Order < Sequel::Model # money_accessor :amount, :currency # end # # order = Order.create(amount: 200, currency: "EUR") # order.amount # => #<Money fractional:20000.0 currency:RUB> # order.currency # => "EUR" def money_accessor(amount_column, currency_column) money_getter(amount_column, currency_column) money_setter(amount_column, currency_column) end def money_getter(amount_column, currency_column) include_accessors_module! @_money_accessors_module.module_eval do define_method(amount_column) do amount, currency = super(), send(currency_column) return unless amount && currency Money.from_amount(amount.to_d, currency) end end end def money_setter(amount_column, currency_column) include_accessors_module! @_money_accessors_module.module_eval do define_method(:"#{amount_column}=") do |value| case value when Money amount = value.to_d currency = value.currency.to_s when nil amount = currency = nil else raise MoneyClassRequired, "#{amount_column} value must be either Money instance or nil" end super(amount) send(:"#{currency_column}=", currency) end end end private def include_accessors_module! return if defined?(@_money_accessors_module) @_money_accessors_module = Module.new include @_money_accessors_module end end end
Version data entries
9 entries across 9 versions & 1 rubygems