Skip to content

Commit

Permalink
disable memoization when block is passed
Browse files Browse the repository at this point in the history
  • Loading branch information
tycooon committed Dec 16, 2017
1 parent 0144ce1 commit 1121978
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,10 @@ a = A.new
a.call # => 42
a.call # => 42
a.call # => 42

# Text will be printed only once.

a.call { 1 } # => 42
# Will print because passing a block disables memoization
```

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

Finally, you can provide a block:

```ruby
a.users {}
```

However, this solution is kind of hacky.

## License

The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
4 changes: 3 additions & 1 deletion lib/memery.rb
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,9 @@ def define_memoized_method!(method_name)
visibility = Memery.method_visibility(self, method_name)

@_memery_module.module_eval do
define_method(method_name) do |*args|
define_method(method_name) do |*args, &block|
return super(*args, &block) if block

@_memery_memoized_values ||= {}

key = [method_name, mod_id].join("_").to_sym
Expand Down
2 changes: 1 addition & 1 deletion lib/memery/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module Memery
VERSION = "0.4.0"
VERSION = "0.5.0"
end
11 changes: 11 additions & 0 deletions spec/memery_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ class C
end
end

context "calling method with block" do
specify do
values = []
values << a.m_args(1, 1) {}
values << a.m_args(1, 1) {}

expect(values).to eq([[1, 1], [1, 1]])
expect(CALLS).to eq([[1, 1], [1, 1]])
end
end

context "calling private method" do
specify do
expect { a.m_private }.to raise_error(NoMethodError, /private method/)
Expand Down

0 comments on commit 1121978

Please sign in to comment.