Class: Telegem::Session::RedisStore
- Inherits:
-
Object
- Object
- Telegem::Session::RedisStore
- Defined in:
- lib/session/redis.rb
Instance Method Summary collapse
- #clear_all ⇒ Object
- #close ⇒ Object
- #delete(key) ⇒ Object
- #get(key) ⇒ Object
- #increment(key, amount = 1, ttl: nil) ⇒ Object
-
#initialize(redis_url: nil, default_ttl: 300, **options) ⇒ RedisStore
constructor
A new instance of RedisStore.
- #set(key, value, ttl: nil) ⇒ Object
Constructor Details
#initialize(redis_url: nil, default_ttl: 300, **options) ⇒ RedisStore
Returns a new instance of RedisStore.
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/session/redis.rb', line 8 def initialize(redis_url: nil, default_ttl: 300, **) @default_ttl = default_ttl # Load redis gem only when needed begin require 'redis' rescue LoadError raise "Redis store requires 'redis' gem. Add 'gem \"redis\"' to your Gemfile." end @redis = if redis_url Redis.new(url: redis_url, **) else Redis.new(**) end end |
Instance Method Details
#clear_all ⇒ Object
64 65 66 67 |
# File 'lib/session/redis.rb', line 64 def clear_all # Be careful with this in production @redis.flushdb end |
#close ⇒ Object
69 70 71 |
# File 'lib/session/redis.rb', line 69 def close @redis.close end |
#delete(key) ⇒ Object
44 45 46 47 |
# File 'lib/session/redis.rb', line 44 def delete(key) key_s = key.to_s @redis.del(key_s) > 0 end |
#get(key) ⇒ Object
34 35 36 37 38 39 40 41 42 |
# File 'lib/session/redis.rb', line 34 def get(key) key_s = key.to_s data = @redis.get(key_s) return nil unless data JSON.parse(data) rescue JSON::ParserError nil end |
#increment(key, amount = 1, ttl: nil) ⇒ Object
49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/session/redis.rb', line 49 def increment(key, amount = 1, ttl: nil) key_s = key.to_s ttl_sec = ttl || @default_ttl # Atomic increment using Redis new_val = @redis.incrby(key_s, amount) # Set expiry if this is a new key or if TTL changed if ttl_sec @redis.expire(key_s, tttl_sec) end new_val end |
#set(key, value, ttl: nil) ⇒ Object
25 26 27 28 29 30 31 32 |
# File 'lib/session/redis.rb', line 25 def set(key, value, ttl: nil) key_s = key.to_s serialized = JSON.generate(value) ttl_sec = ttl || @default_ttl @redis.setex(key_s, ttl_sec, serialized) value end |