Class: Rack::Cache::EntityStore::MemCache

Inherits:
Rack::Cache::EntityStore show all
Extended by:
Utils
Defined in:
lib/rack/cache/entitystore.rb

Overview

Stores entity bodies in memcached.

Constant Summary

Constants inherited from Rack::Cache::EntityStore

DISK, FILE, HEAP, MEM, MEMCACHE, MEMCACHED

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(server = "localhost:11211", options = {}) ⇒ MemCache

Returns a new instance of MemCache.



155
156
157
158
159
160
161
162
163
# File 'lib/rack/cache/entitystore.rb', line 155

def initialize(server="localhost:11211", options={})
  @cache =
    if server.respond_to?(:stats)
      server
    else
      require 'memcached'
      Memcached.new(server, options)
    end
end

Instance Attribute Details

#cacheObject (readonly)

The underlying Memcached instance used to communicate with the memcahced daemon.



153
154
155
# File 'lib/rack/cache/entitystore.rb', line 153

def cache
  @cache
end

Class Method Details

.resolve(uri) ⇒ Object

Create MemCache store for the given URI. The URI must specify a host and may specify a port, namespace, and options:

memcached://example.com:11211/namespace?opt1=val1&opt2=val2

Query parameter names and values are documented with the memcached library: tinyurl.com/4upqnd



202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rack/cache/entitystore.rb', line 202

def self.resolve(uri)
  server = "#{uri.host}:#{uri.port || '11211'}"
  options = parse_query(uri.query)
  options.keys.each do |key|
    value =
      case value = options.delete(key)
      when 'true' ; true
      when 'false' ; false
      else value.to_sym
      end
    options[k.to_sym] = value
  end
  options[:namespace] = uri.path.sub(/^\//, '')
  new server, options
end

Instance Method Details

#exist?(key) ⇒ Boolean

Returns:

  • (Boolean)


165
166
167
168
169
170
# File 'lib/rack/cache/entitystore.rb', line 165

def exist?(key)
  cache.append(key, '')
  true
rescue Memcached::NotStored
  false
end

#open(key) ⇒ Object



178
179
180
181
182
183
184
# File 'lib/rack/cache/entitystore.rb', line 178

def open(key)
  if data = read(key)
    [data]
  else
    nil
  end
end

#read(key) ⇒ Object



172
173
174
175
176
# File 'lib/rack/cache/entitystore.rb', line 172

def read(key)
  cache.get(key, false)
rescue Memcached::NotFound
  nil
end

#write(body) ⇒ Object



186
187
188
189
190
191
# File 'lib/rack/cache/entitystore.rb', line 186

def write(body)
  buf = StringIO.new
  key, size = slurp(body){|part| buf.write(part) }
  cache.set(key, buf.string, 0, false)
  [key, size]
end