Class: ActiveJsonModel::ActiveRecordEncryptedType

Inherits:
ActiveRecordType
  • Object
show all
Defined in:
lib/active_json_model/active_record_encrypted_type.rb

Overview

Allows instances of ActiveJsonModels to be serialized JSONB columns for ActiveRecord models.

class Credentials < ::ActiveJsonModel
  def self.encrypted_attribute_type
    ActiveRecordEncryptedType.new(Credentials)
  end
end

class Integration < ActiveRecord::Base
  attribute :credentials, Credentials.encrypted_attribute_type
end

Instance Method Summary collapse

Methods inherited from ActiveRecordType

#initialize

Constructor Details

This class inherits a constructor from ActiveJsonModel::ActiveRecordType

Instance Method Details

#cast(value) ⇒ Object



29
30
31
32
33
34
35
# File 'lib/active_json_model/active_record_encrypted_type.rb', line 29

def cast(value)
  if value.is_a?(@clazz)
    value
  elsif value.is_a?(::Array)
    @clazz.load(value)
  end
end

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Override to handle issues comparing hashes encoded as strings, where the actual order doesn’t matter.

Returns:

  • (Boolean)


58
59
60
61
62
63
64
65
66
67
68
69
# File 'lib/active_json_model/active_record_encrypted_type.rb', line 58

def changed_in_place?(raw_old_value, new_value)
  if raw_old_value.nil? || new_value.nil?
    raw_old_value == new_value
  else
    # Decode is necessary because postgres can change the order of hashes. Round-tripping on the new value side
    # is to handle any dates that might be rendered as strings.
    decoded_raw = ::ActiveSupport::JSON.decode(raw_old_value)
    round_tripped_new = ::ActiveSupport::JSON.decode(new_value.class.dump(new_value))

    decoded_raw != round_tripped_new
  end
end

#deserialize(value) ⇒ Object



37
38
39
40
41
42
43
44
# File 'lib/active_json_model/active_record_encrypted_type.rb', line 37

def deserialize(value)
  if String === value
      decoded = SymmetricEncryption.decrypt(value, type: :json) rescue nil
    @clazz.load(decoded)
  else
    super
  end
end

#serialize(value) ⇒ Object



46
47
48
49
50
51
52
53
54
55
# File 'lib/active_json_model/active_record_encrypted_type.rb', line 46

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

#typeObject



25
26
27
# File 'lib/active_json_model/active_record_encrypted_type.rb', line 25

def type
  :string
end