Module: AttrKeyring::ActiveRecord::ClassMethods

Defined in:
lib/attr_keyring/active_record.rb

Instance Method Summary collapse

Instance Method Details

#attr_encrypt(*attributes) ⇒ Object



8
9
10
11
12
13
14
15
16
# File 'lib/attr_keyring/active_record.rb', line 8

def attr_encrypt(*attributes)
  self.keyring_attrs ||= []
  keyring_attrs.push(*attributes)

  attributes.each do |attribute|
    define_attr_encrypt_writer(attribute)
    define_attr_encrypt_reader(attribute)
  end
end

#attr_keyring(keyring, encryptor: Encryptor::AES128CBC) ⇒ Object



4
5
6
# File 'lib/attr_keyring/active_record.rb', line 4

def attr_keyring(keyring, encryptor: Encryptor::AES128CBC)
  self.keyring = Keyring.new(keyring, encryptor)
end

#define_attr_encrypt_reader(attribute) ⇒ Object



32
33
34
35
36
37
38
39
40
41
# File 'lib/attr_keyring/active_record.rb', line 32

def define_attr_encrypt_reader(attribute)
  define_method(attribute) do
    encrypted_value = public_send("encrypted_#{attribute}")

    return unless encrypted_value

    keyring_id = public_send(keyring_column_name)
    self.class.keyring.decrypt(encrypted_value, keyring_id)
  end
end

#define_attr_encrypt_writer(attribute) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/attr_keyring/active_record.rb', line 18

def define_attr_encrypt_writer(attribute)
  define_method("#{attribute}=") do |value|
    return attr_reset_column(attribute) if value.nil?

    stored_keyring_id = public_send(keyring_column_name)
    keyring_id = stored_keyring_id || self.class.keyring.current_key&.id
    encrypted_value = self.class.keyring.encrypt(value, keyring_id)

    public_send("#{keyring_column_name}=", keyring_id) unless stored_keyring_id
    public_send("encrypted_#{attribute}=", encrypted_value)
    attr_encrypt_digest(attribute, value)
  end
end