Module: Vidibus::Secure::Mongoid::ClassMethods

Defined in:
lib/vidibus/secure/mongoid.rb

Instance Method Summary collapse

Instance Method Details

#attr_encrypted(*args) ⇒ Object

Sets encrypted attributes.



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

def attr_encrypted(*args)
  key = ENV["VIDIBUS_SECURE_KEY"]
  options = args.extract_options!
  for field in args

    # Define Mongoid field
    encrypted_field = "#{field}_encrypted"
    self.send(:field, encrypted_field, :type => BSON::Binary)

    # Define setter
    class_eval <<-EOV
      def #{field}=(value)
        self.#{encrypted_field} = value ? Vidibus::Secure.encrypt(value, "#{key}") : nil
      end
    EOV

    # Define getter
    class_eval <<-EOV
      def #{field}
        Vidibus::Secure.decrypt(#{encrypted_field}, "#{key}") if #{encrypted_field}
      end
    EOV
  end
end