diff --git a/lib/memery.rb b/lib/memery.rb index e84c995..fbfae58 100644 --- a/lib/memery.rb +++ b/lib/memery.rb @@ -35,10 +35,12 @@ def included(base = nil, &block) extend ModuleMethods module ClassMethods - def memoize(method_name, condition: nil, ttl: nil) + def memoize(*method_names, condition: nil, ttl: nil) prepend_memery_module! - define_memoized_method!(method_name, condition: condition, ttl: ttl) - method_name + method_names.each do |method_name| + define_memoized_method!(method_name, condition: condition, ttl: ttl) + end + method_names.length > 1 ? method_names : method_names.first end def memoized?(method_name) diff --git a/spec/memery_spec.rb b/spec/memery_spec.rb index cc95be6..dbc1f55 100644 --- a/spec/memery_spec.rb +++ b/spec/memery_spec.rb @@ -134,12 +134,33 @@ def self.macro(name) macro memoize def g; end end +class H + include Memery + + [:a, :b, :m, :n, :x, :y].each do |name| + define_method(name) do + CALLS << name + name + end + end + + memoize :m, :n + memoize :x, :y, ttl: 3 +end + RSpec.describe Memery do subject(:a) { A.new } before { CALLS.clear } before { B_CALLS.clear } + let(:unmemoized_class) do + Class.new do + include Memery + attr_reader :a, :b, :m, :n, :x, :y + end + end + context "methods without args" do specify do values = [ a.m, a.m_nil, a.m, a.m_nil ] @@ -366,6 +387,40 @@ def self.macro(name) end end + describe "with multiple methods" do + let(:h) { H.new } + + specify do + values = [h.m, h.n, h.m, h.n] + expect(values).to eq([:m, :n, :m, :n]) + expect(CALLS).to eq([:m, :n]) + end + + specify do + values = [h.x, h.y, h.x, h.y] + expect(values).to eq([:x, :y, :x, :y]) + expect(CALLS).to eq([:x, :y]) + end + + specify do + expect(unmemoized_class.memoize(:x, :y, ttl: 3)).to eq([:x, :y]) + end + end + + describe ".memoize return value" do + specify do + expect(unmemoized_class.memoize(:x)).to eq(:x) + expect(unmemoized_class.memoize(:m, ttl: 3)).to eq(:m) + expect(unmemoized_class.memoize(:a, condition: -> { 1 == 2 })).to eq(:a) + end + + specify do + expect(unmemoized_class.memoize(:x, :y)).to eq([:x, :y]) + expect(unmemoized_class.memoize(:m, :n, ttl: 3)).to eq([:m, :n]) + expect(unmemoized_class.memoize(:a, :b, condition: -> { 1 == 2 })).to eq([:a, :b]) + end + end + describe ".memoized?" do subject { object.memoized?(method_name) }