Module: Lite::Encryption::Attribute

Defined in:
lib/lite/encryption/attribute.rb

Instance Method Summary collapse

Instance Method Details

#attr_encrypt(*fields, **opts) ⇒ Object

rubocop:disable Metrics/MethodLength



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/lite/encryption/attribute.rb', line 8

def attr_encrypt(*fields, **opts)
  class_eval do
    fields.each do |field|
      define_method("#{field}=") do |value|
        return if value.nil?

        encrypted_value = Lite::Encryption::Message.encrypt(value, opts)
        send("encrypted_#{field}=", encrypted_value)
      end

      define_method(field) do
        encrypted_value = send("encrypted_#{field}")
        return if encrypted_value.blank?

        Lite::Encryption::Message.decrypt(encrypted_value, opts)
      end

      define_method("decrypted_#{field}") do
        send(field)
      end
    end
  end
end