Skip to content

Commit 1121978

Browse files
committed
disable memoization when block is passed
1 parent 0144ce1 commit 1121978

File tree

4 files changed

+26
-3
lines changed

4 files changed

+26
-3
lines changed

README.md

+11-1
Original file line numberDiff line numberDiff line change
@@ -24,8 +24,10 @@ a = A.new
2424
a.call # => 42
2525
a.call # => 42
2626
a.call # => 42
27-
2827
# Text will be printed only once.
28+
29+
a.call { 1 } # => 42
30+
# Will print because passing a block disables memoization
2931
```
3032

3133
## Difference with other gems
@@ -75,6 +77,14 @@ Alternatively, you can clear the whole instance's cache:
7577
a.clear_memery_cache!
7678
```
7779

80+
Finally, you can provide a block:
81+
82+
```ruby
83+
a.users {}
84+
```
85+
86+
However, this solution is kind of hacky.
87+
7888
## License
7989

8090
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).

lib/memery.rb

+3-1
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,9 @@ def define_memoized_method!(method_name)
3838
visibility = Memery.method_visibility(self, method_name)
3939

4040
@_memery_module.module_eval do
41-
define_method(method_name) do |*args|
41+
define_method(method_name) do |*args, &block|
42+
return super(*args, &block) if block
43+
4244
@_memery_memoized_values ||= {}
4345

4446
key = [method_name, mod_id].join("_").to_sym

lib/memery/version.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# frozen_string_literal: true
22

33
module Memery
4-
VERSION = "0.4.0"
4+
VERSION = "0.5.0"
55
end

spec/memery_spec.rb

+11
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,17 @@ class C
8989
end
9090
end
9191

92+
context "calling method with block" do
93+
specify do
94+
values = []
95+
values << a.m_args(1, 1) {}
96+
values << a.m_args(1, 1) {}
97+
98+
expect(values).to eq([[1, 1], [1, 1]])
99+
expect(CALLS).to eq([[1, 1], [1, 1]])
100+
end
101+
end
102+
92103
context "calling private method" do
93104
specify do
94105
expect { a.m_private }.to raise_error(NoMethodError, /private method/)

0 commit comments

Comments
 (0)