Skip to content

Commit

Permalink
Support globally disabling memoization
Browse files Browse the repository at this point in the history
Fixes #11
  • Loading branch information
danielwestendorf committed Sep 13, 2024
1 parent 992862f commit 7df6b67
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 0 deletions.
11 changes: 11 additions & 0 deletions lib/ttl_memoizeable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ module TTLMemoizeable
TTLMemoizationError = Class.new(StandardError)
SetupMutex = Mutex.new

@disabled = false

def self.disable!
@disabled = true
end

def self.enable!
@disabled = false
end

def ttl_memoized_method(method_name, ttl: 1000)
raise TTLMemoizationError, "Method not defined: #{method_name}" unless method_defined?(method_name) || private_method_defined?(method_name)

Expand Down Expand Up @@ -60,6 +70,7 @@ def ttl_memoized_method(method_name, ttl: 1000)
end

define_method ttl_exceeded_method_name do
return true if TTLMemoizeable.instance_variable_get(:@disabled)
return true unless instance_variable_defined?(value_variable_name)

compared_to = time_based_ttl ? ttl.ago : 0
Expand Down
37 changes: 37 additions & 0 deletions spec/ttl_memoizeable_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

RSpec.describe TTLMemoizeable do
before { stub_const("Klass", klass) if klass }
after { described_class.enable! }

let(:klass) { integer_ttl_klass }

Expand Down Expand Up @@ -330,4 +331,40 @@ def bar
end.each(&:join)
end
end

describe ".disable!" do
context "it bypasses the cached value" do
let(:klass) { integer_ttl_klass }

before { described_class.disable! }

it "only calls #expensive_bar twice" do
expect(Klass).to receive(:expensive_bar).and_call_original.exactly(11)

11.times do
expect(Klass.bar).to eq(1)
end
end
end
end

describe ".enable!" do
context "it bypasses the cached value" do
let(:klass) { integer_ttl_klass }

before { }

it "only calls #expensive_bar once" do
expect(Klass).to receive(:expensive_bar).and_call_original.once

described_class.disable!
Klass.bar
described_class.enable!

3.times do
expect(Klass.bar).to eq(1)
end
end
end
end
end

0 comments on commit 7df6b67

Please sign in to comment.