diff --git a/lib/rack/attack/store_proxy.rb b/lib/rack/attack/store_proxy.rb index 6f6a507..abd9089 100644 --- a/lib/rack/attack/store_proxy.rb +++ b/lib/rack/attack/store_proxy.rb @@ -14,6 +14,8 @@ module Rack if defined?(::Redis::Store) && store.is_a?(::Redis::Store) RedisStoreProxy.new(store) + elsif defined?(::Dalli) && store.is_a?(::Dalli::Client) + DalliProxy.new(store) else store end @@ -52,6 +54,34 @@ module Rack end end + + class DalliProxy < SimpleDelegator + def initialize(client) + super(client) + end + + def read(key) + with do |client| + client.get(key) + end + rescue Dalli::DalliError + end + + def write(key, value, options={}) + with do |client| + client.set(key, value, options.fetch(:expires_in, 0), raw: true) + end + rescue Dalli::DalliError + end + + def increment(key, amount, options={}) + with do |client| + client.incr(key, amount, options.fetch(:expires_in, 0), amount) + end + rescue Dalli::DalliError + end + + end end end end diff --git a/spec/integration/rack_attack_cache_spec.rb b/spec/integration/rack_attack_cache_spec.rb index 06079ce..adc755a 100644 --- a/spec/integration/rack_attack_cache_spec.rb +++ b/spec/integration/rack_attack_cache_spec.rb @@ -19,6 +19,7 @@ describe Rack::Attack::Cache do ActiveSupport::Cache::MemoryStore.new, ActiveSupport::Cache::DalliStore.new("localhost"), ActiveSupport::Cache::RedisStore.new("localhost"), + Dalli::Client.new, Redis::Store.new ] @@ -108,4 +109,36 @@ describe Rack::Attack::Cache do end end + describe "should not error if memcached is not running" do + before { + Dalli.logger.level = Logger::FATAL + @cache = Rack::Attack::Cache.new + @key = "rack::attack:cache-test-key" + @expires_in = 1 + @cache.store = Dalli::Client.new('127.0.0.1:22122') + } + + after { + Dalli.logger.level = Logger::INFO + } + + describe "write" do + it "should not raise exception" do + @cache.write("cache-test-key", "foobar", 1) + end + end + + describe "read" do + it "should not raise exception" do + @cache.read("cache-test-key") + end + end + + describe "do_count" do + it "should not raise exception" do + @cache.send(:do_count, @key, @expires_in) + end + end + end + end