Class: Mint::MintMoneyType

Inherits:
ActiveRecord::Type::Value
  • Object
show all
Defined in:
lib/minting/money_attribute/money_type.rb

Overview

MintMoneyType

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(currency:, column_type: ActiveRecord::Type::Decimal.new) ⇒ MintMoneyType

Returns a new instance of MintMoneyType.



6
7
8
9
10
# File 'lib/minting/money_attribute/money_type.rb', line 6

def initialize(currency:, column_type: ActiveRecord::Type::Decimal.new)
  @currency = currency
  @column_type = column_type
  super()
end

Class Method Details

.typeObject



45
46
47
# File 'lib/minting/money_attribute/money_type.rb', line 45

def self.type
  :mint_type
end

Instance Method Details

#assert_valid_value(value) ⇒ Object

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/minting/money_attribute/money_type.rb', line 12

def assert_valid_value(value)
  case value
  when NilClass, Numeric, String then return
  when Mint::Money
    return if value.currency == @currency

    message = "'#{value.inspect}' has different currency. Only #{@currency.code} allowed."
  else
    message = "'#{value.inspect}' is not a valid type for the attribute."
  end
  raise ArgumentError, message
end

#deserialize(value) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/minting/money_attribute/money_type.rb', line 25

def deserialize(value)
  return nil unless value

  if @column_type.is_a?(ActiveRecord::Type::Integer)
    Mint.money(value * @currency.multiplier, @currency)
  else
    Mint.money(value, @currency)
  end
end

#serialize(value) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/minting/money_attribute/money_type.rb', line 35

def serialize(value)
  return nil unless value

  if @column_type.is_a?(ActiveRecord::Type::Integer)
    value.fractional
  else
    value.to_d
  end
end