Class: MoneyAttribute::Type
- Inherits:
-
ActiveRecord::Type::Value
- Object
- ActiveRecord::Type::Value
- MoneyAttribute::Type
- Defined in:
- lib/money_attribute/type.rb
Overview
Type
Instance Method Summary collapse
- #assert_valid_value(value) ⇒ Object
- #cast(value) ⇒ Object
- #deserialize(value) ⇒ Object
-
#initialize(currency:, column_type: ActiveRecord::Type::Decimal.new) ⇒ Type
constructor
A new instance of Type.
- #serialize(value) ⇒ Object
Constructor Details
#initialize(currency:, column_type: ActiveRecord::Type::Decimal.new) ⇒ Type
Returns a new instance of Type.
6 7 8 9 10 |
# File 'lib/money_attribute/type.rb', line 6 def initialize(currency:, column_type: ActiveRecord::Type::Decimal.new) @currency = currency @column_type = column_type super() end |
Instance Method Details
#assert_valid_value(value) ⇒ Object
20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/money_attribute/type.rb', line 20 def assert_valid_value(value) case value when NilClass, Numeric, String then return when Mint::Money return if value.currency == @currency = "'#{value.inspect}' has different currency. Only #{@currency.code} allowed." else = "'#{value.inspect}' is not a valid type for the attribute." end raise ArgumentError, end |
#cast(value) ⇒ Object
12 13 14 15 16 17 18 |
# File 'lib/money_attribute/type.rb', line 12 def cast(value) if value.is_a?(String) Mint::Money.parse(value, @currency) else super end end |
#deserialize(value) ⇒ Object
33 34 35 36 37 38 39 40 41 |
# File 'lib/money_attribute/type.rb', line 33 def deserialize(value) return nil unless value if @column_type.is_a?(ActiveRecord::Type::Integer) Mint::Money.from_subunits(value, @currency) else Mint::Money.from(value, @currency) end end |
#serialize(value) ⇒ Object
43 44 45 46 47 48 49 50 51 |
# File 'lib/money_attribute/type.rb', line 43 def serialize(value) return nil unless value if @column_type.is_a?(ActiveRecord::Type::Integer) value.subunits else value.to_d end end |