Module: Teak::AttrEncrypted::DSL::ClassMethods

Defined in:
lib/teak/attr_encrypted/dsl.rb

Instance Method Summary collapse

Instance Method Details

#attr_encrypted(attr_name, ciphertext_attr_name: nil, kek_provider: nil, context: nil) ⇒ Object



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
40
41
42
43
44
# File 'lib/teak/attr_encrypted/dsl.rb', line 13

def attr_encrypted(attr_name, ciphertext_attr_name: nil, kek_provider: nil, context: nil)
  real_field = ciphertext_attr_name || "#{attr_name}_enc"
  real_field_assign = "#{real_field}="
  encryptor = Teak::AttrEncrypted::Encryptor.new(kek_provider || Teak::AttrEncrypted.default_kek_provider)

  context_callable =
    if context.is_a?(Symbol)
      proc { send(context) }
    elsif context.is_a?(Proc)
      context
    else
      proc { context }
    end

  define_method "#{attr_name}=" do |value|
    if value.nil? || value.empty?
      send(real_field_assign, value)
      return value
    end

    send(real_field_assign, encryptor.encrypt(value, instance_exec(&context_callable)))
  end

  define_method attr_name do
    envelope = send(real_field)
    if envelope.nil? || envelope.empty?
      envelope
    else
      encryptor.decrypt(send(real_field), instance_exec(&context_callable))
    end
  end
end