Commit 87d2a09

mo khan <mo@mokhan.ca>
2013-12-27 17:54:15
add identity map.
1 parent 6d6bb89
Changed files (3)
lib/nasty/identity_map.rb
@@ -0,0 +1,23 @@
+module Nasty
+  class IdentityMap
+    def initialize(items = {})
+      @items = items
+    end
+
+    def add(item)
+      @items[item.id] = item
+    end
+
+    def has_item_for?(id)
+      @items.has_key?(id)
+    end
+
+    def item_for(id)
+      @items[id]
+    end
+
+    def evict(item)
+      @items.reject! { |key, value| key == item.id }
+    end
+  end
+end
lib/nasty.rb
@@ -3,6 +3,7 @@ require "nasty/block_specification"
 require "nasty/command"
 require "nasty/composite_command"
 require "nasty/expose_binding"
+require "nasty/identity_map"
 require "nasty/kernel"
 require "nasty/lambda_behaviours"
 require "nasty/lazy"
spec/unit/identity_map_spec.rb
@@ -0,0 +1,49 @@
+require "spec_helper"
+
+module Nasty
+  describe IdentityMap do
+    let(:sut) { IdentityMap.new }
+
+    context "when an item is added" do
+      let(:item) { Item.new(:id => 187) }
+
+      before { sut.add(item) }
+
+      it "indicates that an item with that id is available" do
+        sut.has_item_for?(item.id).should be_true
+      end
+
+      it "loads the item" do
+        sut.item_for(item.id).should == item
+      end
+
+      context "when an item is evicted" do
+        before { sut.evict(item) }
+
+        it "indicates that it does not have an item for the evicted id" do
+          sut.has_item_for?(item.id).should be_false
+        end
+
+        it "returns nothing" do
+          sut.item_for(item.id).should be_nil
+        end
+      end
+    end
+
+    context "when no items have been added" do
+      it "indicates that it does not have any items for any id" do
+        (0..10).each do |i|
+          sut.has_item_for?(i).should be_false
+        end
+      end
+    end
+
+    class Item
+      attr_reader :id
+
+      def initialize(attributes)
+        @id = attributes[:id]
+      end
+    end
+  end
+end