module AttrSecure

Constants

ADAPTERS

All the available adapters. The order in this list matters, as only the first valid adapter will be used

VERSION

Public Instance Methods

attr_secure(*attributes) click to toggle source

Generates attr_accessors that encrypt and decrypt attributes transparently

# File lib/attr_secure.rb, line 21
def attr_secure(*attributes)
  options = {
    :encryption_class => Secure,
    :secret_class     => Secret,
    :env              => ENV
  }.merge!(attributes.last.is_a?(Hash) ? attributes.pop : {})

  attribute = attributes.first

  define_method("#{attribute}=") do |value|
    adapter = self.class.attr_secure_adapter
    secret  = options[:secret_class].new(options).call(self)
    crypter = options[:encryption_class].new(secret)
    value   = crypter.encrypt(value)

    adapter.write_attribute self, attribute, value
  end

  define_method("#{attribute}") do
    adapter = self.class.attr_secure_adapter
    secret  = options[:secret_class].new(options).call(self)
    crypter = options[:encryption_class].new(secret)
    value   = adapter.read_attribute(self, attribute)

    crypter.decrypt value
  end
end
attr_secure_adapter() click to toggle source
# File lib/attr_secure.rb, line 49
def attr_secure_adapter
  ADAPTERS.find {|a| a.valid?(self) }
end