Class: Exchange::Cache::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/exchange/cache/redis.rb

Overview

A class that cooperates with the redis gem and the redis key value store to cache the data from the exchange api in redis

Examples:

Activate caching via redis by setting the cache in the configuration to :redis

Exchange::Configuration.define do |c| 
  c.cache = :redis
  c.cache_host = 'Your redis host' 
  c.cache_port = 'Your redis port (an Integer)'
end

Author:

  • Beat Richartz

Since:

  • 0.1

Version:

  • 0.1

Instance Method Summary collapse

Instance Method Details

#cached(api, opts = {}) { ... } ⇒ Object

returns either cached data from the redis client or calls the block and caches it in redis. This method has to be the same in all the cache classes in order for the configuration binding to work

Parameters:

  • api (Exchange::ExternalAPI::Subclass)

    The API class the data has to be stored for

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

    the options to cache with

Options Hash (opts):

  • :at (Time)

    the historic time of the exchange rates to be cached

Yields:

  • This method takes a mandatory block with an arity of 0 and calls it if no cached result is available

Raises:

Since:

  • 0.1


46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/exchange/cache/redis.rb', line 46

def cached api, opts={}, &block         
  if result = client.get(key(api, opts))
    result = opts[:plain] ? result : result.decachify
  else
    result = super
    if result && !result.to_s.empty?
      client.set key(api, opts), result.cachify
      client.expire key(api, opts), config.expire == :daily ? 86400 : 3600
    end
  end
  
  result
end

#client::Redis

instantiates a redis client and memoizes it in a class variable. Use this client to access redis data. For further explanation of use visit the redis gem documentation

Examples:

Exchange::Cache::Redis.client.set('FOO', 'BAR')

Returns:

  • (::Redis)

    an instance of the redis client gem class

Since:

  • 0.1


27
28
29
30
# File 'lib/exchange/cache/redis.rb', line 27

def client
  Exchange::GemLoader.new('redis').try_load unless defined?(::Redis)
  @client ||= ::Redis.new(:host => config.host, :port => config.port)
end

#wipe_client!Object

Wipe the client instance variable

Since:

  • 0.1


34
35
36
# File 'lib/exchange/cache/redis.rb', line 34

def wipe_client!
  @client = nil
end