Class: Whoosh::Cache::RedisStore
- Inherits:
-
Object
- Object
- Whoosh::Cache::RedisStore
- Defined in:
- lib/whoosh/cache/redis_store.rb
Class Method Summary collapse
Instance Method Summary collapse
- #clear ⇒ Object
- #close ⇒ Object
- #delete(key) ⇒ Object
- #fetch(key, ttl: nil) ⇒ Object
- #get(key) ⇒ Object
-
#initialize(url:, default_ttl: 300, pool_size: 5) ⇒ RedisStore
constructor
A new instance of RedisStore.
- #set(key, value, ttl: nil) ⇒ Object
Constructor Details
#initialize(url:, default_ttl: 300, pool_size: 5) ⇒ RedisStore
Returns a new instance of RedisStore.
21 22 23 24 25 26 27 |
# File 'lib/whoosh/cache/redis_store.rb', line 21 def initialize(url:, default_ttl: 300, pool_size: 5) unless self.class.available? raise Errors::DependencyError, "Cache Redis store requires the 'redis' gem" end @redis = Redis.new(url: url) @default_ttl = default_ttl end |
Class Method Details
.available? ⇒ Boolean
9 10 11 12 13 14 15 16 17 18 19 |
# File 'lib/whoosh/cache/redis_store.rb', line 9 def self.available? if @redis_available.nil? @redis_available = begin require "redis" true rescue LoadError false end end @redis_available end |
Instance Method Details
#clear ⇒ Object
59 60 61 62 63 64 |
# File 'lib/whoosh/cache/redis_store.rb', line 59 def clear @redis.flushdb true rescue => e false end |
#close ⇒ Object
66 67 68 69 |
# File 'lib/whoosh/cache/redis_store.rb', line 66 def close @redis.close rescue => e end |
#delete(key) ⇒ Object
53 54 55 56 57 |
# File 'lib/whoosh/cache/redis_store.rb', line 53 def delete(key) @redis.del(key) > 0 rescue => e false end |
#fetch(key, ttl: nil) ⇒ Object
45 46 47 48 49 50 51 |
# File 'lib/whoosh/cache/redis_store.rb', line 45 def fetch(key, ttl: nil) existing = get(key) return existing unless existing.nil? value = yield set(key, value, ttl: ttl) Serialization::Json.decode(Serialization::Json.encode(value)) end |
#get(key) ⇒ Object
29 30 31 32 33 34 35 |
# File 'lib/whoosh/cache/redis_store.rb', line 29 def get(key) raw = @redis.get(key) return nil unless raw Serialization::Json.decode(raw) rescue => e nil end |
#set(key, value, ttl: nil) ⇒ Object
37 38 39 40 41 42 43 |
# File 'lib/whoosh/cache/redis_store.rb', line 37 def set(key, value, ttl: nil) ttl ||= @default_ttl @redis.set(key, Serialization::Json.encode(value), ex: ttl) true rescue => e false end |