require "spec_helper" require "ruby_ext/declarative_cache" 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 DeclarativeCache.cache_method CachedClass, :value2_get 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 "clear_cache_method" do o = CachedClass.new o.value = 0 o.value_get.should == 0 o.value = 1 o.value_get.should == 0 o.clear_cache_method 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 allow to cache twice" do CachedClass4.cache_method :value_get lambda{CachedClass4.cache_method :value_get}.should raise_error(/twice/) end end