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 "      def \#{field}=(value)\n        self.\#{encrypted_field} = value ? Vidibus::Secure.encrypt(value, \"\#{key}\") : nil\n      end\n    EOV\n\n    # Define getter\n    class_eval <<-EOV\n      def \#{field}\n        Vidibus::Secure.decrypt(\#{encrypted_field}, \"\#{key}\") if \#{encrypted_field}\n      end\n    EOV\n  end\nend\n"