Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to clear all cached entries for an instance #6

Merged
merged 1 commit into from
Feb 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions lib/memo_pad/memo.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 16 additions & 7 deletions test/test_memo_pad.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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
Expand All @@ -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