Created
February 2, 2010 02:07
-
-
Save gerad/292282 to your computer and use it in GitHub Desktop.
simple encrypted fields in rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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