module MoneyColumn::ActiveRecordHooks::ClassMethods

Attributes

money_column_options[R]

Public Instance Methods

money_column(*columns, currency_column: nil, currency: nil, currency_read_only: false, coerce_null: false) click to toggle source
# File lib/money_column/active_record_hooks.rb, line 73
def money_column(*columns, currency_column: nil, currency: nil, currency_read_only: false, coerce_null: false)
  @money_column_options ||= {}

  options = normalize_money_column_options(
    currency_column: currency_column,
    currency: currency,
    currency_read_only: currency_read_only,
    coerce_null: coerce_null
  )

  if options[:currency_column]
    clear_cache_on_currency_change(options[:currency_column])
  end

  columns.flatten.each do |column|
    column_string = column.to_s.freeze

    @money_column_options[column_string] = options

    attribute(column_string, MoneyColumn::ActiveRecordType.new)

    define_method column do
      read_money_attribute(column_string)
    end

    define_method "#{column}=" do |money|
      write_money_attribute(column_string, money)
    end
  end
end

Private Instance Methods

clear_cache_on_currency_change(currency_column) click to toggle source
Calls superclass method
# File lib/money_column/active_record_hooks.rb, line 121
def clear_cache_on_currency_change(currency_column)
  return if money_column_options.any? { |_, opt| opt[:currency_column] == currency_column }

  define_method "#{currency_column}=" do |value|
    clear_money_column_cache
    super(value)
  end
end
inherited(subclass) click to toggle source
Calls superclass method
# File lib/money_column/active_record_hooks.rb, line 130
def inherited(subclass)
  subclass.instance_variable_set('@money_column_options', money_column_options.dup) if money_column_options
  super
end
normalize_money_column_options(options) click to toggle source
# File lib/money_column/active_record_hooks.rb, line 106
def normalize_money_column_options(options)
  raise ArgumentError, 'cannot set both :currency_column and :currency options' if options[:currency] && options[:currency_column]
  raise ArgumentError, 'must set one of :currency_column or :currency options' unless options[:currency] || options[:currency_column]

  if options[:currency]
    options[:currency] = Money::Currency.find!(options[:currency]).to_s.freeze
    options[:currency_read_only] = true
  end

  if options[:currency_column]
    options[:currency_column] = options[:currency_column].to_s.freeze
  end
  options
end