Module: Mongoid::EncryptedField::ClassMethods

Defined in:
lib/mongoid-encrypted-fields/fields/encrypted_field.rb

Constant Summary collapse

MARKER =

Used to identify encrypted strings

Base64.encode64('\x02`{~MeF~}`\x03').chomp

Instance Method Summary collapse

Instance Method Details

#convert(object) ⇒ Object

Raises:

  • (NotImplementedError)


57
58
59
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 57

def convert(object)
  raise NotImplementedError.new("convert must be implemented")
end

#decrypt(encrypted) ⇒ Object



69
70
71
72
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 69

def decrypt(encrypted)
  unmarked = encrypted.slice(MARKER.size..-1)
  EncryptedFields.cipher.decrypt(unmarked)
end

#demongoize(object) ⇒ Object

Get the object as it was stored in the database, and instantiate this custom class from it.



30
31
32
33
34
35
36
37
38
39
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 30

def demongoize(object)
  #EncryptedFields.logger.debug "#{name}##{__method__.to_s}: #{object.inspect}"
  case
    when object.is_a?(self.class) || object.blank?
      object
    else
      decrypted = is_encrypted?(object) ? decrypt(object) : object
      convert(decrypted)
  end
end

#encrypt(plaintext) ⇒ Object



64
65
66
67
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 64

def encrypt(plaintext)
  encrypted = EncryptedFields.cipher.encrypt(plaintext).chomp
  MARKER + encrypted
end

#is_encrypted?(object) ⇒ Boolean

Returns:

  • (Boolean)


74
75
76
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 74

def is_encrypted?(object)
  object.is_a?(::String) && object.start_with?(MARKER)
end

#mongoize(object) ⇒ Object Also known as: evolve

Takes any possible object and converts it to how it would be stored in the database.



42
43
44
45
46
47
48
49
50
51
52
# File 'lib/mongoid-encrypted-fields/fields/encrypted_field.rb', line 42

def mongoize(object)
  #EncryptedFields.logger.debug "#{name}##{__method__.to_s}: #{object.inspect}"
  case
    when object.is_a?(self.class)
      object.mongoize
    when object.blank? || is_encrypted?(object)
      object
    else
      convert(object).mongoize
  end
end