require "more/spec_helper" describe 'DeclarativeCache' do class CachedClass attr_accessor :value def value_get; @value end cache_method :value_get attr_accessor :value2 def value2_get; @value2 end attr_accessor :params def params_get param; @params[param] end attr_accessor :multiplier def *(arg) @multiplier * arg end cache_method_with_params '*' end RubyExt::DeclarativeCache.cache_method CachedClass, :value2_get RubyExt::DeclarativeCache.cache_method_with_params CachedClass, :params_get it "Simple Cache" do o = CachedClass.new o.value = 0 o.value2 = 0 o.value_get.should == 0 o.value2_get.should == 0 o.value = 1 o.value2 = 1 o.value_get.should == 0 o.value2_get.should == 0 end it "should define _with_cache and _without_cache methods" do o = CachedClass.new # without params o.value = 0 o.value_get.should == 0 o.value = 1 o.value_get.should == 0 o.value_get_with_cache.should == 0 o.value_get_without_cache.should == 1 # with params o.params = {a: :b} o.params_get(:a).should == :b o.params = {a: :c} o.params_get(:a).should == :b o.params_get_with_cache(:a).should == :b o.params_get_without_cache(:a).should == :c end it "clear_cache" do o = CachedClass.new o.value = 0 o.value_get.should == 0 o.value = 1 o.value_get.should == 0 Module.clear_cache o o.value_get.should == 1 end it "should check for parameters" do o = CachedClass.new lambda{o.value_get(1)}.should raise_error(/cache_method_with_params/) end it "Cache With Params" do o = CachedClass.new o.params = {a: :b} o.params_get(:a).should == :b o.params = {a: :c} o.params_get(:a).should == :b end it "should works with operators" do o = CachedClass.new o.multiplier = 2 (o * 2).should == 4 o.multiplier = 3 (o * 2).should == 4 end class CachedClass2 class << self attr_accessor :value def value_get; @value end cache_method :value_get end end it "Simple Cache" do CachedClass2.value = 0 CachedClass2.value_get.should == 0 CachedClass2.value = 1 CachedClass2.value_get.should == 0 end module CachedModule attr_accessor :value def value_get; @value end cache_method :value_get end class CachedClass3 include CachedModule end it "should also works with modules (from error)" do o = CachedClass.new o.value = 0 o.value_get.should == 0 o.value = 1 o.value_get.should == 0 end class CachedClass4 attr_accessor :value def value_get; @value end end it "should not cache twice, and should works" do CachedClass4.cache_method :value_get Object.should_receive(:warn){|msg| msg =~ /twice/} CachedClass4.cache_method :value_get o = CachedClass.new o.value = 0 o.value_get.should == 0 o.value = 1 o.value_get.should == 0 end end