Class: Marfa::Cache

Inherits:
Object show all
Defined in:
lib/marfa/cache.rb

Overview

Redis-cache wrapper

Instance Method Summary collapse

Constructor Details

#initializeCache

Returns a new instance of Cache.



7
8
9
10
# File 'lib/marfa/cache.rb', line 7

def initialize
  @config = Marfa.config.cache
  @redis = Redis.new(host: @config[:host], port: @config[:port], db: @config[:db])
end

Instance Method Details

#delete(key) ⇒ Object

Delete data from cache

Examples:

Marfa.cache.delete('key')

Parameters:



50
51
52
# File 'lib/marfa/cache.rb', line 50

def delete(key)
  @redis.del(key)
end

#delete_by_pattern(pattern) ⇒ Object

Delete data from cache by pattern

Examples:

Marfa.cache.delete_by_pattern('pattern')

Parameters:

  • pattern (String)

    pattern



58
59
60
61
# File 'lib/marfa/cache.rb', line 58

def delete_by_pattern(pattern)
  keys = @redis.keys("*#{pattern}*")
  @redis.del(*keys) unless keys.empty?
end

#exist?(key) ⇒ Boolean

Check that key exist in cache

Examples:

Marfa.cache.exist?('key')

Parameters:

Returns:

  • (Boolean)


41
42
43
44
# File 'lib/marfa/cache.rb', line 41

def exist?(key)
  return unless @config[:enabled]
  @redis.exists(key)
end

#get(key) ⇒ String, Nil

Get data from cache

Examples:

Marfa.cache.get('key')

Parameters:

Returns:

  • (String)

    data from cache

  • (Nil)


32
33
34
# File 'lib/marfa/cache.rb', line 32

def get(key)
  @redis.get(key)
end

#set(key, value, time = nil) ⇒ Object

Write data to cache

Examples:

Marfa.cache.set('key', 'value', 7200)


15
16
17
18
19
20
21
22
23
24
# File 'lib/marfa/cache.rb', line 15

def set(key, value, time = nil)
  return unless @config[:enabled]
  return if time.zero?

  if time.is_a? Numeric
    @redis.set(key, value, ex: time) # ex - is seconds
  else
    @redis.set(key, value) #infinite
  end
end