From 218479f71c861db79ccce8e12c4cb59d0a63cc77 Mon Sep 17 00:00:00 2001 From: Erik Michaels-Ober Date: Fri, 1 Jun 2012 18:28:14 -1000 Subject: [PATCH] Implement identity map! --- lib/twitter/base.rb | 12 +++++++++++- lib/twitter/identity_map.rb | 8 ++++++++ spec/twitter/base_spec.rb | 6 ++++++ 3 files changed, 25 insertions(+), 1 deletion(-) create mode 100644 lib/twitter/identity_map.rb diff --git a/lib/twitter/base.rb b/lib/twitter/base.rb index 48c38f4fd..cf5531d25 100644 --- a/lib/twitter/base.rb +++ b/lib/twitter/base.rb @@ -1,8 +1,12 @@ +require 'twitter/identity_map' + module Twitter class Base attr_accessor :attrs alias :to_hash :attrs + @@identity_map = IdentityMap.new + # Define methods that retrieve the value from an initialized instance variable Hash, using the attribute as a key # # @overload self.lazy_attr_reader(attr) @@ -19,12 +23,18 @@ def self.lazy_attr_reader(*attrs) end end + def self.new(attrs={}) + @@identity_map[self.name] ||= {} + @@identity_map[self.name][Marshal.dump(attrs)] || super(attrs) + end + # Initializes a new Base object # # @param attrs [Hash] # @return [Twitter::Base] def initialize(attrs={}) - @attrs = attrs.dup + @attrs = attrs + @@identity_map[self.class.name][Marshal.dump(attrs)] = self end # Initializes a new Base object diff --git a/lib/twitter/identity_map.rb b/lib/twitter/identity_map.rb new file mode 100644 index 000000000..3966ca1a1 --- /dev/null +++ b/lib/twitter/identity_map.rb @@ -0,0 +1,8 @@ +module Twitter + + # Tracks objects to help ensure that each object gets loaded only once. + # See: http://www.martinfowler.com/eaaCatalog/identityMap.html + class IdentityMap < Hash + end + +end diff --git a/spec/twitter/base_spec.rb b/spec/twitter/base_spec.rb index ff7b3516a..72664ab30 100644 --- a/spec/twitter/base_spec.rb +++ b/spec/twitter/base_spec.rb @@ -26,4 +26,10 @@ end end + describe "identical objects" do + it "should have the same object_id" do + @base.object_id.should == Twitter::Base.new('id' => 1).object_id + end + end + end