Class: StoreModel::Types::One

Inherits:
OneBase
  • Object
show all
Defined in:
lib/store_model/types/one.rb

Overview

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

Instance Method Summary collapse

Methods inherited from OneBase

#changed_in_place?

Constructor Details

#initialize(model_klass) ⇒ StoreModel::Types::One

Initializes type for model class

Parameters:



14
15
16
# File 'lib/store_model/types/one.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

Parameters:

  • value (Object)

    a value to cast

Returns:

  • StoreModel::Model



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

def cast_value(value)
  case value
  when String then decode_and_initialize(value)
  when Hash then model_instance(value)
  when @model_klass, nil then value
  else raise_cast_error(value)
  end
rescue ActiveModel::UnknownAttributeError => e
  handle_unknown_attribute(value, e)
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



47
48
49
50
51
52
53
54
# File 'lib/store_model/types/one.rb', line 47

def serialize(value)
  case value
  when Hash, @model_klass
    ActiveSupport::JSON.encode(value, serialize_unknown_attributes: true)
  else
    super
  end
end

#typeSymbol

Returns type

Returns:

  • (Symbol)


21
22
23
# File 'lib/store_model/types/one.rb', line 21

def type
  :json
end