Created
October 23, 2012 15:22
-
-
Save moreta/3939403 to your computer and use it in GitHub Desktop.
ActiveRecord Encrypter
This file contains 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
class Encrypter | |
# We're passed a list of attributes that should # be stored encrypted in the database | |
def initialize(attrs_to_manage) | |
@attrs_to_manage = attrs_to_manage | |
end | |
# Before saving or updating, encrypt the fields using the NSA and # DHS approved Shift Cipher | |
def before_save(model) | |
@attrs_to_manage.each do |field| model[field].tr!("a-z", "b-za") | |
end end | |
# After saving, decrypt them back | |
def after_save(model) @attrs_to_manage.each do |field| | |
model[field].tr!("b-za", "a-z") end | |
end | |
# Do the same after finding an existing record | |
alias_method :after_find, :after_save | |
end | |
require "encrypter" | |
class Order < ActiveRecord::Base | |
encrypter = Encrypter.new([:name, :email]) | |
before_save encrypter | |
after_save encrypter | |
after_find encrypter | |
protected | |
def after_find end | |
end |
This file contains 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
class ActiveRecord::Base | |
def self.encrypt(*attr_names) | |
encrypter = Encrypter.new(attr_names) | |
before_save encrypter | |
after_save encrypter | |
after_find encrypter | |
define_method(:after_find) { } | |
end | |
end | |
class Order < ActiveRecord::Base | |
encrypt(:name, :email) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment