From afecd0c58b746d64241fb0f44235391132ad28c8 Mon Sep 17 00:00:00 2001 From: Brandon Keepers Date: Sat, 3 Sep 2011 00:18:12 -0400 Subject: [PATCH] Unset all instance variables when reloading --- lib/mongo_mapper/plugins/document.rb | 11 +++++------ lib/mongo_mapper/plugins/keys.rb | 10 ---------- test/functional/test_document.rb | 5 +++++ 3 files changed, 10 insertions(+), 16 deletions(-) diff --git a/lib/mongo_mapper/plugins/document.rb b/lib/mongo_mapper/plugins/document.rb index 0cb693784..735beb5df 100644 --- a/lib/mongo_mapper/plugins/document.rb +++ b/lib/mongo_mapper/plugins/document.rb @@ -21,13 +21,12 @@ def destroyed? def reload if doc = collection.find_one(:_id => id) - tap do |instance| - instance.class.associations.each_value do |association| - get_proxy(association).reset - end - instance.clear_keys! - instance.attributes = doc + self.class.associations.each_value do |association| + get_proxy(association).reset end + instance_variables.each { |ivar| instance_variable_set(ivar, nil) } + self.attributes = doc + self else raise DocumentNotFound, "Document match #{_id.inspect} does not exist in #{collection.name} collection" end diff --git a/lib/mongo_mapper/plugins/keys.rb b/lib/mongo_mapper/plugins/keys.rb index 908f3c650..7951286ea 100644 --- a/lib/mongo_mapper/plugins/keys.rb +++ b/lib/mongo_mapper/plugins/keys.rb @@ -172,16 +172,6 @@ def persisted? !new? && !destroyed? end - def clear_keys! - keys.each_key do |key| - if respond_to?(:"#{key}=") - self.send(:"#{key}=", nil) - else - self[key] = nil - end - end - end - def attributes=(attrs) return if attrs.blank? diff --git a/test/functional/test_document.rb b/test/functional/test_document.rb index 220141adf..4579ce20a 100644 --- a/test/functional/test_document.rb +++ b/test/functional/test_document.rb @@ -245,6 +245,11 @@ def setup @instance.destroy assert_raises(MongoMapper::DocumentNotFound) { @instance.reload } end + + should "clear keys that were removed from the database" do + @instance.unset(:age) + @instance.reload.age.should be_nil + end end context "database has keys not defined in model" do