Skip to content

Commit

Permalink
Merge pull request #6 from dribbble/cache-clear
Browse files Browse the repository at this point in the history
Add ability to clear all cached entries for an instance
pbyrne authored Feb 16, 2024
2 parents 1454371 + 077c21d commit 64bd6c3
Showing 2 changed files with 20 additions and 7 deletions.
4 changes: 4 additions & 0 deletions lib/memo_pad/memo.rb
Original file line number Diff line number Diff line change
@@ -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
23 changes: 16 additions & 7 deletions test/test_memo_pad.rb
Original file line number Diff line number Diff line change
@@ -54,15 +54,15 @@ def with_arguments(foo)
end

describe MemoPad do
subject { ClassWithMemoPad.new }

describe "::VERSION" do
it "has a version number" do
refute_nil MemoPad::VERSION
end
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

0 comments on commit 64bd6c3

Please sign in to comment.