Created
December 5, 2013 12:49
-
-
Save danielnc/7804638 to your computer and use it in GitHub Desktop.
attr_encrypted supporting different classes
Based on
http://stackoverflow.com/questions/17482507/correct-way-to-handle-multiparameter-attributes-corresponding-to-virtual-attribu
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
if defined?(ActiveRecord::Base) | |
module AttrEncrypted | |
module Adapters | |
module ActiveRecord | |
protected | |
class EncryptedAttributeClassWrapper | |
attr_reader :klass | |
def initialize(klass); @klass = klass; end | |
end | |
def encrypted_attribute_class_wrappers | |
@encrypted_attribute_class_wrappers ||= {} | |
end | |
alias_method :attr_encrypted_base, :attr_encrypted | |
def attr_encrypted(*args) | |
options = args.last.is_a?(Hash) ? args.pop : {} | |
if klass = options.delete(:class) | |
attribute_sym = args.first.to_sym | |
self.encrypted_attribute_class_wrappers[attribute_sym] = EncryptedAttributeClassWrapper.new(klass) | |
end | |
new_args = args + [options] | |
attr_encrypted_base *new_args | |
end | |
end | |
end | |
end | |
class ActiveRecord::Base | |
protected | |
alias_method :column_for_attribute_base, :column_for_attribute | |
def column_for_attribute(attribute) | |
attribute_sym = attribute.to_sym | |
if encrypted = self.class.encrypted_attributes[attribute_sym] | |
column_info = self.class.send(:encrypted_attribute_class_wrappers)[attribute_sym] | |
column_info ||= column_for_attribute_base(encrypted[:attribute]) | |
column_info | |
else | |
column_for_attribute_base(attribute) | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment