Class: Tml::CacheAdapters::Redis

Inherits:
Tml::Cache show all
Defined in:
lib/tml/cache_adapters/redis.rb

Instance Method Summary collapse

Methods inherited from Tml::Cache

#cached_by_source?, #enabled?, #info, #reset_version, #segmented?, #update_version, #upgrade_version, #version, #versioned_key, #warn

Constructor Details

#initializeRedis

Returns a new instance of Redis.



38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/tml/cache_adapters/redis.rb', line 38

def initialize
  config = Tml.config.cache

  config[:host] ||= 'localhost'
  config[:port] ||= 6379

  if config[:host].index(':')
    parts = config[:host].split(':')
    config[:host] = parts.first
    config[:port] = parts.last
  end

  @cache = ::Redis.new(config)
end

Instance Method Details

#cache_nameObject



53
54
55
# File 'lib/tml/cache_adapters/redis.rb', line 53

def cache_name
  'redis'
end

#clear(opts = {}) ⇒ Object



117
118
119
# File 'lib/tml/cache_adapters/redis.rb', line 117

def clear(opts = {})
  info('Cache clear has no effect')
end

#delete(key, opts = {}) ⇒ Object



101
102
103
104
105
106
107
# File 'lib/tml/cache_adapters/redis.rb', line 101

def delete(key, opts = {})
  info("Cache delete: #{key}")
  @cache.del(versioned_key(key, opts))
rescue Exception => ex
  warn("Failed to delete data: #{ex.message}")
  key
end

#exist?(key, opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


109
110
111
112
113
114
115
# File 'lib/tml/cache_adapters/redis.rb', line 109

def exist?(key, opts = {})
  data = @cache.exist(versioned_key(key, opts))
  not data.nil?
rescue Exception => ex
  warn("Failed to check if key exists: #{ex.message}")
  false
end

#fetch(key, opts = {}) ⇒ Object



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
# File 'lib/tml/cache_adapters/redis.rb', line 61

def fetch(key, opts = {})
  data = @cache.get(versioned_key(key, opts))
  if data
    info("Cache hit: #{key}")

    begin
      return JSON.parse(data)
    rescue Exception => ex
      warn("Failed to parse data: #{ex.message}")
    end
  end

  info("Cache miss: #{key}")

  return nil unless block_given?

  data = yield

  store(key, data)

  data
rescue Exception => ex
  warn("Failed to retrieve data: #{ex.message}")
  return nil unless block_given?
  yield
end

#read_only?Boolean

Returns:

  • (Boolean)


57
58
59
# File 'lib/tml/cache_adapters/redis.rb', line 57

def read_only?
  false
end

#store(key, data, opts = {}) ⇒ Object



88
89
90
91
92
93
94
95
96
97
98
99
# File 'lib/tml/cache_adapters/redis.rb', line 88

def store(key, data, opts = {})
  info("Cache store: #{key}")

  ttl = opts[:ttl] || Tml.config.cache[:timeout]
  versioned_key = versioned_key(key, opts)

  @cache.set(versioned_key, data.to_json)
  @cache.expire(versioned_key, ttl) if ttl and ttl > 0
rescue Exception => ex
  warn("Failed to store data: #{ex.message}")
  data
end