Class: StoreModel::Types::JsonType

Inherits:
ActiveModel::Type::Value
  • Object
show all
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

Constructor Details

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

Initializes type for model class

Parameters:



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

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/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

Parameters:

  • raw_old_value (Object)

    old value

  • new_value (Object)

    new value

Returns:

  • (Boolean)


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.

Parameters:

  • value (Object)

    value to serialize

Returns:

  • (String)

    serialized value



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

#typeSymbol

Returns type

Returns:

  • (Symbol)


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

def type
  :json
end