lib/mongoid/kms.rb in mongoid-kms-0.0.20 vs lib/mongoid/kms.rb in mongoid-kms-0.0.21

- old
+ new

@@ -80,49 +80,13 @@ # Class methods module ClassMethods def inherited(child) child.kms_field_map = self.kms_field_map.clone - - child.kms_field_map.each do |field_name, args| - child.add_secure_field(field_name, args) - end + super(child) end - def add_secure_field(field_name, args) - encrypted_field_name = get_encrypted_field_name(field_name) - - define_attribute_methods field_name.to_sym - before_save :set_kms_values - - kms_field_map[field_name.to_s] = {context: args.delete(:context), type: args[:type]} - - field encrypted_field_name, type: Mongoid::Kms.bson_class::Binary - - self.class_eval do - define_method(field_name) do - instance_variable_get("@#{field_name}") || begin - raw = send("kms_secure_#{field_name}") - - if raw.nil? - raw - else - v = self.class.decrypt_field(self, field_name, raw) - instance_variable_set("@#{field_name}", v) - v - end - end - end - - define_method("#{field_name}=") do |value| - self.send("#{field_name}_will_change!") - instance_variable_set("@#{field_name}", value) - end - end - end - - def encrypt_field(object, field_name, value) Mongoid::Kms.kms.encrypt({ key_id: Mongoid::Kms.key, plaintext: value, encryption_context: kms_context(object, field_name) @@ -176,10 +140,36 @@ def get_encrypted_field_name(field_name) "kms_secure_#{field_name}" end def secure_field(field_name, args) - add_secure_field(field_name, args) + encrypted_field_name = get_encrypted_field_name(field_name) + + define_attribute_methods field_name.to_sym + before_save :set_kms_values + + kms_field_map[field_name.to_s] = {context: args.delete(:context), type: args[:type]} + + field encrypted_field_name, type: Mongoid::Kms.bson_class::Binary + + define_method(field_name) do + instance_variable_get("@#{field_name}") || begin + raw = send("kms_secure_#{field_name}") + + if raw.nil? + raw + else + v = self.class.decrypt_field(self, field_name, raw) + instance_variable_set("@#{field_name}", v) + v + end + end + end + + define_method("#{field_name}=") do |value| + self.send("#{field_name}_will_change!") + instance_variable_set("@#{field_name}", value) + end end end module Errors class ConfigurationError < RuntimeError; end