Class: ActiveRecord::Type::Json

Inherits:
ActiveModel::Type::Value show all
Includes:
ActiveModel::Type::Helpers::Mutable
Defined in:
activerecord/lib/active_record/type/json.rb

Constant Summary collapse

JSON_ENCODER =
ActiveSupport::JSON::Encoding.json_encoder.new(escape: false)

Instance Attribute Summary

Attributes inherited from ActiveModel::Type::Value

#limit, #precision, #scale

Instance Method Summary collapse

Methods included from ActiveModel::Type::Helpers::Mutable

#cast, #mutable?

Methods inherited from ActiveModel::Type::Value

#==, #as_json, #assert_valid_value, #binary?, #cast, #changed?, #force_equality?, #hash, #initialize, #map, #mutable?, #serializable?, #serialized?, #type_cast_for_schema, #value_constructed_by_mass_assignment?

Methods included from ActiveModel::Type::SerializeCastValue

included, #initialize, #itself_if_serialize_cast_value_compatible, serialize

Methods included from ActiveSupport::Concern

#append_features, #class_methods, extended, #included, #prepend_features, #prepended

Constructor Details

This class inherits a constructor from ActiveModel::Type::Value

Instance Method Details

#accessorObject



38
39
40
# File 'activerecord/lib/active_record/type/json.rb', line 38

def accessor
  ActiveRecord::Store::StringKeyedHashAccessor
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:



34
35
36
# File 'activerecord/lib/active_record/type/json.rb', line 34

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

#deserialize(value) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'activerecord/lib/active_record/type/json.rb', line 14

def deserialize(value)
  return value unless value.is_a?(::String)
  begin
    ActiveSupport::JSON.decode(value)
  rescue JSON::ParserError => e
    # NOTE: This may hide json with duplicate keys. We don't really want to just ignore it
    # but it's the best we can do in order to still allow updating columns that somehow already
    # contain invalid json from some other source.
    # See https://github.com/rails/rails/pull/55536
    ActiveSupport.error_reporter.report(e, source: "application.active_record")
    nil
  end
end

#serialize(value) ⇒ Object



30
31
32
# File 'activerecord/lib/active_record/type/json.rb', line 30

def serialize(value)
  JSON_ENCODER.encode(value) unless value.nil?
end

#typeObject



10
11
12
# File 'activerecord/lib/active_record/type/json.rb', line 10

def type
  :json
end