Class: StoreModel::Types::JsonType
- Inherits:
-
ActiveModel::Type::Value
- Object
- ActiveModel::Type::Value
- StoreModel::Types::JsonType
- Defined in:
- lib/store_model/types/json_type.rb
Overview
Implements ActiveModel::Type::Value type for handling an instance of StoreModel::Model
Instance Method Summary collapse
-
#cast_value(value) ⇒ Object
Casts
value
from DB or user to StoreModel::Model instance. -
#changed_in_place?(raw_old_value, new_value) ⇒ Boolean
Determines whether the mutable value has been modified since it was read.
-
#initialize(model_klass) ⇒ StoreModel::Types::JsonType
constructor
Initializes type for model class.
-
#serialize(value) ⇒ String
Casts a value from the ruby type to a type that the database knows how to understand.
-
#type ⇒ Symbol
Returns type.
Constructor Details
#initialize(model_klass) ⇒ StoreModel::Types::JsonType
Initializes type for model class
14 15 16 |
# File 'lib/store_model/types/json_type.rb', line 14 def initialize(model_klass) @model_klass = model_klass end |
Instance Method Details
#cast_value(value) ⇒ Object
Casts value
from DB or user to StoreModel::Model instance
30 31 32 33 34 35 36 37 38 39 |
# File 'lib/store_model/types/json_type.rb', line 30 def cast_value(value) case value when String then decode_and_initialize(value) when Hash then @model_klass.new(value) when @model_klass, nil then value else raise_cast_error(value) end rescue ActiveModel::UnknownAttributeError => e handle_unknown_attribute(value, e) end |
#changed_in_place?(raw_old_value, new_value) ⇒ Boolean
Determines whether the mutable value has been modified since it was read
62 63 64 |
# File 'lib/store_model/types/json_type.rb', line 62 def changed_in_place?(raw_old_value, new_value) cast_value(raw_old_value) != new_value end |
#serialize(value) ⇒ String
Casts a value from the ruby type to a type that the database knows how to understand.
47 48 49 50 51 52 53 54 |
# File 'lib/store_model/types/json_type.rb', line 47 def serialize(value) case value when Hash, @model_klass ActiveSupport::JSON.encode(value) else super end end |
#type ⇒ Symbol
Returns type
21 22 23 |
# File 'lib/store_model/types/json_type.rb', line 21 def type :json end |