Class: StoreModel::Types::One
- Defined in:
- lib/store_model/types/one.rb
Overview
Implements ActiveModel::Type::Value type for handling an instance of StoreModel::Model
Instance Attribute Summary
Attributes inherited from Base
Instance Method Summary collapse
-
#cast_value(value) ⇒ Object
Casts
valuefrom DB or user to StoreModel::Model instance. -
#deserialize(value) ⇒ Object
rubocop:disable Style/RescueModifier.
-
#initialize(model_klass) ⇒ StoreModel::Types::One
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.
Methods inherited from OneBase
Constructor Details
#initialize(model_klass) ⇒ StoreModel::Types::One
Initializes type for model class
14 15 16 17 |
# File 'lib/store_model/types/one.rb', line 14 def initialize(model_klass) @model_klass = model_klass super() end |
Instance Method Details
#cast_value(value) ⇒ Object
Casts value from DB or user to StoreModel::Model instance
31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
# File 'lib/store_model/types/one.rb', line 31 def cast_value(value) # rubocop:disable Metrics/MethodLength return nil if value.nil? if value.is_a?(String) decode_and_initialize(value) elsif value.is_a?(@model_klass) value elsif value.respond_to?(:to_h) # Hash itself included model_instance(value.to_h) else raise_cast_error(value) end rescue ActiveModel::UnknownAttributeError => e handle_unknown_attribute(value, e) end |
#deserialize(value) ⇒ Object
rubocop:disable Style/RescueModifier
73 74 75 76 77 78 79 80 81 82 83 84 |
# File 'lib/store_model/types/one.rb', line 73 def deserialize(value) case value when String payload = ActiveSupport::JSON.decode(value) rescue {} model_instance(deserialize_by_types(payload)) when ::Hash model_instance(deserialize_by_types(value)) when nil nil else raise_cast_error(value) end end |
#serialize(value) ⇒ String
Casts a value from the ruby type to a type that the database knows how to understand.
53 54 55 56 57 58 59 60 61 62 63 64 |
# File 'lib/store_model/types/one.rb', line 53 def serialize(value) case value when @model_klass ActiveSupport::JSON.encode(value, serialize_unknown_attributes: value.serialize_unknown_attributes?, serialize_enums_using_as_json: value.serialize_enums_using_as_json?) when ::Hash ActiveSupport::JSON.encode(value) else super end end |
#type ⇒ Symbol
Returns type
22 23 24 |
# File 'lib/store_model/types/one.rb', line 22 def type :json end |