Class: TwitterCache::Redis

Inherits:
Object
  • Object
show all
Includes:
Helpers
Defined in:
lib/twitter_cache/redis.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Helpers

#cache, #config

Constructor Details

#initializeRedis

Returns a new instance of Redis.



9
10
11
12
13
# File 'lib/twitter_cache/redis.rb', line 9

def initialize
  redis_url = ENV['REDIS_URL'] || config.redis
  redis = ::Redis.new(url: redis_url)
  @client = ::Redis::Namespace.new(:twitter_cache_gem, redis: redis)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



15
16
17
# File 'lib/twitter_cache/redis.rb', line 15

def method_missing(name, *args)
  client.send(name, *args)
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



7
8
9
# File 'lib/twitter_cache/redis.rb', line 7

def client
  @client
end

Instance Method Details

#get(key, ttl: nil) ⇒ Object



19
20
21
22
23
24
25
26
27
# File 'lib/twitter_cache/redis.rb', line 19

def get(key, ttl: nil)
  stored = client.get(key)
  return Oj.load(stored, symbolize_keys: true) if stored
  return nil unless block_given?

  value = yield
  set(key, value, ttl: ttl)
  value
end

#set(key, value, ttl: nil) ⇒ Object



29
30
31
32
# File 'lib/twitter_cache/redis.rb', line 29

def set(key, value, ttl: nil)
  client.set(key, Oj.dump(value))
  client.expire(ttl) if ttl
end