Module: EncryptionAccessor::AccessorMethods

Included in:
ActiveRecord::Base
Defined in:
lib/encryption_accessor/accessor_methods.rb

Instance Method Summary collapse

Instance Method Details

#encryption_accessor(*fields) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/encryption_accessor/accessor_methods.rb', line 5

def encryption_accessor(*fields)
  fields.each do |field|
    force_implement_field_setter!(field)

    define_method(:"#{field}_with_encryption=") do |value|
      self.send(:"#{field}_without_encryption=", value)
      write_attribute(:"#{field}", AESCrypt.encrypt(read_attribute(:"#{field}"))) unless value.nil?
    end

    self.send :alias_method_chain, :"#{field}=", :encryption

    define_method(:"#{field}_decrypt") do
      blob_value = self.read_attribute(:"#{field}")
      return if blob_value.nil?
      AESCrypt.decrypt(blob_value)
    end

    define_method(:"#{field}") do
      self.send(:"#{field}_decrypt")
    end

    define_method(:"#{field}_encrypted") do
      self.attributes["#{field}"]
    end
    define_method(:"#{field}") do
      self.send(:"#{field}_decrypt")
    end
    define_method(:"#{field}_encrypt!") do
      self.send(:"#{field}_with_encryption=", self.attributes["#{field}"])
    end
    define_method(:"#{field}_decrypt!") do
      self.send(:"#{field}=", self.send(:"#{field}_decrypt"))
    end
  end
end