diff --git a/lib/memo_pad/memo.rb b/lib/memo_pad/memo.rb index 8fe6b8f..c514266 100644 --- a/lib/memo_pad/memo.rb +++ b/lib/memo_pad/memo.rb @@ -17,6 +17,10 @@ def fetch(method_name, *args, &block) write(method_name, *args, value: block.call) end + def clear + cache.clear + end + def read(method_name, *args) cache[method_name].fetch(args, nil) end diff --git a/test/test_memo_pad.rb b/test/test_memo_pad.rb index 70c24b8..99a7d3f 100644 --- a/test/test_memo_pad.rb +++ b/test/test_memo_pad.rb @@ -54,6 +54,8 @@ def with_arguments(foo) end describe MemoPad do + subject { ClassWithMemoPad.new } + describe "::VERSION" do it "has a version number" do refute_nil MemoPad::VERSION @@ -61,8 +63,6 @@ def with_arguments(foo) end describe "#fetch" do - subject { ClassWithMemoPad.new } - it "calls the block once for methods with no arguments" do assert subject.no_arguments_truthy subject.no_arguments_truthy @@ -79,7 +79,6 @@ def with_arguments(foo) end describe "#write" do - subject { ClassWithMemoPad.new } let(:result) { rand } it "writes the given value to be read later" do @@ -99,7 +98,6 @@ def with_arguments(foo) end describe "#read" do - subject { ClassWithMemoPad.new } let(:arg) { rand } it "returns nil if no cached value present" do @@ -122,7 +120,6 @@ def with_arguments(foo) end describe "#read!" do - subject { ClassWithMemoPad.new } let(:arg) { rand } it "raises KeyError if no cached value present" do @@ -143,12 +140,24 @@ def with_arguments(foo) assert_equal result, subject.memo_pad.read!(:with_arguments, arg) assert_raises(KeyError) do - assert_nil subject.memo_pad.read!(:with_arguments, :foo) + subject.memo_pad.read!(:with_arguments, :foo) end assert_raises(KeyError) do - assert_nil subject.memo_pad.read!(:with_arguments) + subject.memo_pad.read!(:with_arguments) end end end + + describe "#clear" do + it "empties any memoized values" do + subject.memo_pad.write(:foo, value: "bar") + subject.memo_pad.write(:bar, :baz, value: "quux") + + subject.memo_pad.clear + + assert_nil subject.memo_pad.read(:foo) + assert_nil subject.memo_pad.read(:bar, :baz) + end + end end