Class: MoneyAttribute::Type
- Inherits:
-
ActiveRecord::Type::Value
- Object
- ActiveRecord::Type::Value
- MoneyAttribute::Type
- Defined in:
- lib/money_attribute/type.rb
Overview
Type
Class Method Summary collapse
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 |
Class Method Details
.type ⇒ Object
52 53 54 |
# File 'lib/money_attribute/type.rb', line 52 def self.type :money end |
Instance Method Details
#assert_valid_value(value) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/money_attribute/type.rb', line 19 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 |
# File 'lib/money_attribute/type.rb', line 12 def cast(value) case value when String then Mint::Money.parse(value, @currency) else super end end |
#deserialize(value) ⇒ Object
32 33 34 35 36 37 38 39 40 |
# File 'lib/money_attribute/type.rb', line 32 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
42 43 44 45 46 47 48 49 50 |
# File 'lib/money_attribute/type.rb', line 42 def serialize(value) return nil unless value if @column_type.is_a?(ActiveRecord::Type::Integer) value.subunits else value.to_d end end |