Class: StoreModel::Types::JsonType

Inherits:
ActiveModel::Type::Value
  • Object
show all
Defined in:
lib/store_model/types/json_type.rb

Instance Method Summary collapse

Constructor Details

#initialize(model_klass) ⇒ JsonType

Returns a new instance of JsonType.



8
9
10
# File 'lib/store_model/types/json_type.rb', line 8

def initialize(model_klass)
  @model_klass = model_klass
end

Instance Method Details

#cast_value(value) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
# File 'lib/store_model/types/json_type.rb', line 16

def cast_value(value)
  case value
  when String then decode_and_initialize(value)
  when Hash then @model_klass.new(value)
  when @model_klass then value
  else
    raise StoreModel::Types::CastError,
          "failed casting #{value.inspect}, only String, " \
          "Hash or #{@model_klass.name} instances are allowed"
  end
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/store_model/types/json_type.rb', line 37

def changed_in_place?(raw_old_value, new_value)
  cast_value(raw_old_value) != new_value
end

#serialize(value) ⇒ Object



28
29
30
31
32
33
34
35
# File 'lib/store_model/types/json_type.rb', line 28

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

#typeObject



12
13
14
# File 'lib/store_model/types/json_type.rb', line 12

def type
  :json
end