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 spec and doc for class methods #3

Merged
merged 1 commit into from
Apr 19, 2018
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
20 changes: 20 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,26 @@ a.call { 1 } # => 42
# Will print because passing a block disables memoization
```

For class methods:

```ruby
class B
class << self
include Memery

memoize def call
puts "calculating"
42
end
end
end

B.call # => 42
B.call # => 42
B.call # => 42
# Text will be printed only once.
```

## Difference with other gems
Memery is very similar to [Memoist](https://github.com/matthewrudy/memoist). The difference is that it doesn't override methods, instead it uses Ruby 2 `Module.prepend` feature. This approach is cleaner and it allows subclasses' methods to work properly: if you redefine a memoized method in a subclass, it's not memoized by default, but you can memoize it normally (without using awkward `identifier: ` argument) and it will just work:

Expand Down
21 changes: 21 additions & 0 deletions spec/memery_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,17 @@ class C
include M
end

class D
class << self
include Memery

memoize def m_args(x, y)
CALLS << [x, y]
[x, y]
end
end
end

RSpec.describe Memery do
before { CALLS.clear }
before { B_CALLS.clear }
Expand Down Expand Up @@ -132,4 +143,14 @@ class C
expect(CALLS).to eq([:m])
end
end

context "class method with args" do
subject(:d) { D }

specify do
values = [ d.m_args(1, 1), d.m_args(1, 1), d.m_args(1, 2) ]
expect(values).to eq([[1, 1], [1, 1], [1, 2]])
expect(CALLS).to eq([[1, 1], [1, 2]])
end
end
end