Class: StoreModel::Types::HashBase

Inherits:
Base
  • Object
show all
Defined in:
lib/store_model/types/hash_base.rb

Overview

Implements type for handling a hash of StoreModel::Model

Direct Known Subclasses

Hash, HashPolymorphic

Instance Attribute Summary

Attributes inherited from Base

#model_klass

Instance Method Summary collapse

Methods inherited from Base

#type

Instance Method Details

#cast_value(value) ⇒ Object

Casts value from DB or user to Hash of StoreModel::Model instances

Parameters:

  • value (Object)

    a value to cast

Returns:

  • Hash



14
15
16
17
18
19
20
21
22
# File 'lib/store_model/types/hash_base.rb', line 14

def cast_value(value)
  case value
  when String then decode_and_initialize(value)
  when ::Hash then ensure_model_class(value)
  when nil then value
  else
    raise_cast_error(value)
  end
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Determines whether the mutable value has been modified since it was read

Parameters:

  • raw_old_value (Object)

    old value

  • new_value (Object)

    new value

Returns:

  • (Boolean)


49
50
51
# File 'lib/store_model/types/hash_base.rb', line 49

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.

Parameters:

  • value (Object)

    value to serialize

Returns:

  • (String)

    serialized value



30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/store_model/types/hash_base.rb', line 30

def serialize(value)
  return super unless value.is_a?(::Hash)
  if value.empty? || value.values.any? { |v| !v.is_a?(StoreModel::Model) }
    return ActiveSupport::JSON.encode(value)
  end

  ActiveSupport::JSON.encode(
    value,
    serialize_unknown_attributes: value.values.first.serialize_unknown_attributes?,
    serialize_enums_using_as_json: value.values.first.serialize_enums_using_as_json?
  )
end