Last active
December 19, 2015 17:38
-
-
Save rcook/5992293 to your computer and use it in GitHub Desktop.
Enable multiparameter attribute form submission for encrypted fields in Ruby on Rails http://stackoverflow.com/questions/17482507/correct-way-to-handle-multiparameter-attributes-corresponding-to-virtual-attribu Simply drop this into config/initializers and use attr_encrypted_default instead of attr_encrypted. I'm working on an update to attr_enc…
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) | |
class ActiveRecord::Base | |
protected | |
class EncryptedAttributeClassWrapper | |
attr_reader :klass | |
def initialize(klass); @klass = klass; end | |
end | |
def self.encrypted_attribute_class_wrappers | |
@encrypted_attribute_class_wrappers ||= {} | |
end | |
# Consider using alias_method_chain to replace | |
# the built-in method. | |
def self.attr_encrypted_default(*args) | |
options = args.last.is_a?(Hash) ? args.pop : {} | |
# Not required functionality, but I'd like to make | |
# attr_encrypted do this natively too. | |
options = { | |
:key => ENV['DEFAULT_FIELD_ENCRYPTION_KEY'], | |
:marshal => true | |
}.merge(options) | |
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 *new_args | |
end | |
# http://stackoverflow.com/questions/17482507/correct-way-to-handle-multiparameter-attributes-corresponding-to-virtual-attribu | |
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.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