Skip to content

Instantly share code, notes, and snippets.

@gerad
Created February 2, 2010 02:07
Show Gist options
  • Save gerad/292282 to your computer and use it in GitHub Desktop.
Save gerad/292282 to your computer and use it in GitHub Desktop.
simple encrypted fields in rails
# extend Encrypter::Encryptable
# encrypt :email, :password
class Encrypter
def self.encrypt val
encrypter.encrypt val
end
def self.decrypt val
encrypter.decrypt val
end
module Encryptable
def self.extended base
def base.encrypt *fields
fields.each do |field|
define_method "#{field}_with_decryption" do
Encrypter.decrypt self.send("#{field}_without_decryption")
end
alias_method_chain field, :decryption
define_method "#{field}_with_encryption=" do |val|
self.send "#{field}_without_encryption=", Encrypter.encrypt(val)
end
alias_method_chain "#{field}=", :encryption
end
end
end
end
private
def self.encrypter
@@encrypter ||= ActiveSupport::MessageEncryptor.new(ActionController::Base.session_options[:secret])
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment