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.



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

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.



169
170
171
# File 'lib/rack/cache/entitystore.rb', line 169

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



225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# File 'lib/rack/cache/entitystore.rb', line 225

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)


181
182
183
184
185
186
# File 'lib/rack/cache/entitystore.rb', line 181

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

#open(key) ⇒ Object



194
195
196
197
198
199
200
# File 'lib/rack/cache/entitystore.rb', line 194

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

#purge(key) ⇒ Object



209
210
211
212
213
214
# File 'lib/rack/cache/entitystore.rb', line 209

def purge(key)
  cache.delete(key)
  nil
rescue Memcached::NotFound
  nil
end

#read(key) ⇒ Object



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

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

#write(body) ⇒ Object



202
203
204
205
206
207
# File 'lib/rack/cache/entitystore.rb', line 202

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