-
Notifications
You must be signed in to change notification settings - Fork 509
/
memcache.rb
98 lines (94 loc) · 2.83 KB
/
memcache.rb
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
module Padrino
module Cache
module Store
##
# Memcache Cache Store
#
class Memcache < Base
##
# Initialize Memcache store with client connection.
#
# @param client
# instance of Memcache library
#
# @example
# Padrino.cache = Padrino::Cache::Store::Memcache.new(::Memcached.new('127.0.0.1:11211'))
# Padrino.cache = Padrino::Cache::Store::Memcache.new(::Memcached.new('127.0.0.1:11211', :exception_retry_limit => 1))
# # or from your app
# set :cache, Padrino::Cache::Store::Memcache.new(::Memcached.new('127.0.0.1:11211'))
# set :cache, Padrino::Cache::Store::Memcache.new(::Memcached.new('127.0.0.1:11211', :exception_retry_limit => 1))
#
# @api public
def initialize(client, options={})
@backend = client
super(options)
end
##
# Return the a value for the given key
#
# @param [String] key
# cache key to retrieve value
#
# @example
# # with MyApp.cache.set('records', records)
# MyApp.cache.get('records')
#
# @api public
def get(key)
@backend.get(key)
rescue Memcached::NotFound
nil
end
##
# Set the value for a given key and optionally with an expire time
# Default expiry time is 86400.
#
# @param [String] key
# cache key
# @param value
# value of cache key
#
# @example
# MyApp.cache.set('records', records)
# MyApp.cache.set('records', records, :expires_in => 30) # => 30 seconds
#
# @api public
def set(key, value, opts = nil)
if opts && opts[:expires_in]
expires_in = opts[:expires_in].to_i
expires_in = (@backend.class.name == "MemCache" ? expires_in : Time.new.to_i + expires_in) if expires_in < EXPIRES_EDGE
@backend.set(key, value, expires_in)
else
@backend.set(key, value)
end
end
##
# Delete the value for a given key
#
# @param [String] key
# cache key
#
# @example
# # with: MyApp.cache.set('records', records)
# MyApp.cache.delete('records')
#
# @api public
def delete(key)
@backend.delete(key)
end
##
# Reinitialize your cache
#
# @example
# # with: MyApp.cache.set('records', records)
# MyApp.cache.flush
# MyApp.cache.get('records') # => nil
#
# @api public
def flush
@backend.respond_to?(:flush_all) ? @backend.flush_all : @backend.flush
end
end # Memcached
end # Store
end # Cache
end # Padrino