Module: Slosilo::EncryptedAttributes::ClassMethods

Defined in:
lib/slosilo/attr_encrypted.rb

Instance Method Summary collapse

Instance Method Details

#attr_encrypted(*a) ⇒ Object

Parameters:

  • options (Hash)
  • :aad (Hash)

    a customizable set of options



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/slosilo/attr_encrypted.rb', line 24

def attr_encrypted *a
  options = a.last.is_a?(Hash) ? a.pop : {}
  aad = options[:aad]
  # note nil.to_s is "", which is exactly the right thing
  auth_data = aad.respond_to?(:to_proc) ? aad.to_proc : proc{ |_| aad.to_s }

  # In ruby 3 .arity for #proc returns both 1 and 2, depends on internal #proc
  # This method is also being called with aad which is string, in such case the arity is 1
  raise ":aad proc must take two arguments" unless (auth_data.arity.abs == 2 || auth_data.arity.abs == 1)

  # push a module onto the inheritance hierarchy
  # this allows calling super in classes
  include(accessors = Module.new)
  accessors.module_eval do 
    a.each do |attr|
      define_method "#{attr}=" do |value|
        super(EncryptedAttributes.encrypt(value, aad: auth_data[self]))
      end
      define_method attr do
        EncryptedAttributes.decrypt(super(), aad: auth_data[self])
      end
    end
  end
end