class StoreModel::Types::ManyBase

Implements ActiveModel::Type::Value type for handling an array of StoreModel::Model

Public Instance Methods

cast_value(value) click to toggle source

Casts value from DB or user to StoreModel::Model instance

@param value [Object] a value to cast

@return StoreModel::Model

# File lib/store_model/types/many_base.rb, line 22
def cast_value(value)
  case value
  when String then decode_and_initialize(value)
  when Array then ensure_model_class(value)
  when nil then value
  else
    raise_cast_error(value)
  end
end
changed_in_place?(raw_old_value, new_value) click to toggle source

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

@param raw_old_value [Object] old value @param new_value [Object] new value

@return [Boolean]

# File lib/store_model/types/many_base.rb, line 53
def changed_in_place?(raw_old_value, new_value)
  cast_value(raw_old_value) != new_value
end
serialize(value) click to toggle source

Casts a value from the ruby type to a type that the database knows how to understand.

@param value [Object] value to serialize

@return [String] serialized value

Calls superclass method
# File lib/store_model/types/many_base.rb, line 38
def serialize(value)
  case value
  when Array
    ActiveSupport::JSON.encode(value)
  else
    super
  end
end
type() click to toggle source

Returns type

@return [Symbol]

# File lib/store_model/types/many_base.rb, line 13
def type
  raise NotImplementedError
end

Protected Instance Methods

cast_model_type_value(_value) click to toggle source
# File lib/store_model/types/many_base.rb, line 63
def cast_model_type_value(_value)
  raise NotImplementedError
end
ensure_model_class(_array) click to toggle source
# File lib/store_model/types/many_base.rb, line 59
def ensure_model_class(_array)
  raise NotImplementedError
end
raise_cast_error(_value) click to toggle source
# File lib/store_model/types/many_base.rb, line 67
def raise_cast_error(_value)
  raise NotImplementedError
end

Private Instance Methods

decode_and_initialize(array_value) click to toggle source

rubocop:disable Style/RescueModifier

# File lib/store_model/types/many_base.rb, line 74
def decode_and_initialize(array_value)
  decoded = ActiveSupport::JSON.decode(array_value) rescue []
  decoded.map { |attributes| cast_model_type_value(attributes) }
end