Class: BungieClient::Cache

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Cache

Initialize handlers of cache client with options

Parameters:

  • options (Hash) (defaults to: {})

    with

Options Hash (options):

  • :client (Class)
    • basic object of cache client, e.g. [Redis]

  • :get (Proc)
    • method for getting data, it gets key of row on call

  • :set (Proc)
    • method for setting data, it gets key, value, ttl on call

  • :ttl (Integer)
    • time to live of row in cache



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/bungie_client/cache.rb', line 32

def initialize(options = {})
  @ttl = (options[:ttl].is_a?(Integer) && options[:ttl] > 0) ? options[:ttl] : 900

  if options[:client].nil?
    raise 'You must define the client initialization.'
  else
    @client = options[:client]
  end

  if options[:get].is_a? Proc
    @get = options[:get]
  else
    raise 'You must define the get method for caching.'
  end

  if options[:set].is_a? Proc
    @set = options[:set]
  else
    raise 'You must define the set method for caching.'
  end
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



2
3
4
# File 'lib/bungie_client/cache.rb', line 2

def client
  @client
end

#ttlObject (readonly)

Returns the value of attribute ttl.



3
4
5
# File 'lib/bungie_client/cache.rb', line 3

def ttl
  @ttl
end

Instance Method Details

#get(key) ⇒ Object

Get value

Parameters:

  • key (String)

Returns:

  • (Object)


10
11
12
13
14
# File 'lib/bungie_client/cache.rb', line 10

def get(key)
  result = @get.call @client, key.to_s

  Marshal.load result unless result.nil?
end

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

Set value

Parameters:

  • key (String)
  • value (Object)

    it can be everything, because it serialized with [Marshal]

  • ttl (Integer|nil) (defaults to: nil)


21
22
23
# File 'lib/bungie_client/cache.rb', line 21

def set(key, value, ttl = nil)
  @set.call @client, key.to_s, Marshal.dump(value), (ttl || @ttl)
end