Class: Exchange::Cache::Memcached

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

Overview

A class that cooperates with the memcached gem to cache the data from the exchange api in memcached

Examples:

Activate caching via memcache by setting the cache in the configuration to :memcached

Exchange::Configuration.define do |c| 
  c.cache = :memcached
  c.cache_host = 'Your memcached host' 
  c.cache_port = 'Your memcached port'
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 memcached client or calls the block and caches it in memcached. 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 for caching

Raises:

Since:

  • 0.1


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

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

#clientDalli::Client

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

Examples:

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

Returns:

  • (Dalli::Client)

    an instance of the dalli gem client class

Since:

  • 0.1


28
29
30
31
# File 'lib/exchange/cache/memcached.rb', line 28

def client
  Exchange::GemLoader.new('dalli').try_load unless defined?(::Dalli)
  @client ||= Dalli::Client.new("#{config.host}:#{config.port}")
end

#wipe_client!Object

Wipe the client instance variable

Since:

  • 0.1


35
36
37
# File 'lib/exchange/cache/memcached.rb', line 35

def wipe_client!
  @client = nil
end