Class: Typhoeus::Cache::Redis

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

Overview

This module provides a simple way to cache HTTP responses in Redis.

Since:

  • 0.5.0

Instance Method Summary collapse

Constructor Details

#initialize(redis = ::Redis.new, options = {}) ⇒ Redis

Returns a new instance of Redis.

Examples:

Set Redis as the Typhoeus cache backend

Typhoeus::Config.cache = Typhoeus::Cache::Redis.new

Parameters:

  • redis (Redis) (defaults to: ::Redis.new)

    A connection to Redis. Defaults to ‘Redis.new`, which uses the `REDIS_URL` environment variable to connect

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

    Options

Options Hash (options):

  • :default_ttl (Integer)

    The default TTL of cached responses in seconds, for requests which do not set a cache_ttl.

Since:

  • 0.5.0



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

def initialize(redis = ::Redis.new, options = {})
  @redis = redis
  @default_ttl = options[:default_ttl]
end

Instance Method Details

#get(request) ⇒ Object

Since:

  • 0.5.0



20
21
22
23
24
# File 'lib/typhoeus/cache/redis.rb', line 20

def get(request)
  serialized_response = @redis.get(request.cache_key)
  return unless serialized_response
  Marshal.load(serialized_response)
end

#set(request, response) ⇒ Object

Since:

  • 0.5.0



26
27
28
29
30
31
32
# File 'lib/typhoeus/cache/redis.rb', line 26

def set(request, response)
  ttl = request.cache_ttl || @default_ttl
  key = request.cache_key
  serialized_response = Marshal.dump(response)
  @redis.set(key, serialized_response)
  @redis.expire(key, ttl) if ttl
end