Class: Marfa::Cache

Inherits:
Object
  • 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

#create_json_key(path) ⇒ String

Create key for json urls

Examples:

Marfa.cache.create_json_key('/get_list.json')

Parameters:

Returns:



73
74
75
# File 'lib/marfa/cache.rb', line 73

def create_json_key(path)
  path.gsub(%r{[/.]}, '_')
end

#create_key(kind, path, tags) ⇒ String

Create key by params

Examples:

Marfa.cache.create_key('block', 'offer/list', ['tag1', 'tag2'])

Parameters:

  • kind (String)

    kind (block or page)

  • path (String)

    path

  • tags (Array)

    tag list

Returns:



64
65
66
# File 'lib/marfa/cache.rb', line 64

def create_key(kind, path, tags)
  kind + '_' + path.tr('/', '_') + '__' + tags.join('_')
end

#delete(key) ⇒ Object

Delete data from cache

Examples:

Marfa.cache.delete('key')

Parameters:



44
45
46
# File 'lib/marfa/cache.rb', line 44

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



52
53
54
55
# File 'lib/marfa/cache.rb', line 52

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)


35
36
37
38
# File 'lib/marfa/cache.rb', line 35

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)


26
27
28
# File 'lib/marfa/cache.rb', line 26

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

#set(key, value, _time = @config[:expiration_time]) ⇒ Object

Write data to cache

Examples:

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


15
16
17
18
# File 'lib/marfa/cache.rb', line 15

def set(key, value, _time = @config[:expiration_time])
  return unless @config[:enabled]
  @redis.set(key, value)
end