Class: ActiveRecordEncryptedString::Type

Inherits:
ActiveRecord::Type::String
  • Object
show all
Defined in:
lib/active_record_encrypted_string/type.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(**options) ⇒ Type

Returns a new instance of Type.



11
12
13
# File 'lib/active_record_encrypted_string/type.rb', line 11

def initialize(**options)
  @salt = options[:salt]
end

Class Method Details

.key_lenObject



6
7
8
# File 'lib/active_record_encrypted_string/type.rb', line 6

def key_len
  ActiveSupport::MessageEncryptor.key_len(ActiveRecordEncryptedString.configuration.cipher_alg)
end

Instance Method Details

#changed_in_place?(raw_old_value, new_value) ⇒ Boolean

Returns:

  • (Boolean)


31
32
33
# File 'lib/active_record_encrypted_string/type.rb', line 31

def changed_in_place?(raw_old_value, new_value)
  deserialize(raw_old_value) != new_value if new_value.is_a?(::String)
end

#deserialize(value) ⇒ Object

ActiveRecord calls deserialize to convert values stored database to Ruby objects



24
25
26
27
28
29
# File 'lib/active_record_encrypted_string/type.rb', line 24

def deserialize(value)
  # expects same behavior as ActiveRecord::Type::String other than decryption
  # https://github.com/rails/rails/blob/5-0-stable/activemodel/lib/active_model/type/value.rb#L21-L23
  v = super(value)
  v.present? ? encryptor.decrypt_and_verify(v) : v
end

#serialize(value) ⇒ Object

ActiveRecord calls serialize to convert Ruby objects to a format that can be understood by database



16
17
18
19
20
21
# File 'lib/active_record_encrypted_string/type.rb', line 16

def serialize(value)
  # expects same behavior as ActiveRecord::Type::String other than encryption
  # https://github.com/rails/rails/blob/5-0-stable/activemodel/lib/active_model/type/immutable_string.rb
  v = super(value)
  v.present? ? encryptor.encrypt_and_sign(v) : v
end