Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
branch: master
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 55 lines (46 sloc) 1.157 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
require 'adapter'
require 'memcached'

module Adapter
  module Memcached
    def read(key)
      decode(client.get(key_for(key)))
    rescue ::Memcached::NotFound
    end

    def write(key, value)
      client.set(key_for(key), encode(value))
    end

    def delete(key)
      read(key).tap { client.delete(key_for(key)) }
    rescue ::Memcached::NotFound
    end

    def clear
      client.flush
    end

    def lock(name, options={}, &block)
      key = key_for(name)
      start = Time.now
      lock_acquired = false
      expiration = options.fetch(:expiration, 1)
      timeout = options.fetch(:timeout, 5)

      while (Time.now - start) < timeout
        begin
          client.add(key, 'locked', expiration)
          lock_acquired = true
          break
        rescue ::Memcached::NotStored
          sleep 0.1
        end
      end

      raise(Adapter::LockTimeout.new(name, timeout)) unless lock_acquired

      begin
        yield
      ensure
        begin
          client.delete(key)
        rescue ::Memcached::NotFound
        end
      end
    end
  end
end

Adapter.define(:memcached, Adapter::Memcached)
Something went wrong with that request. Please try again.