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

  • default_ttl (Integer)

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

Since:

  • 0.5.0


13
14
15
16
# File 'lib/typhoeus/cache/redis.rb', line 13

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

Instance Method Details

#get(request) ⇒ Object

Since:

  • 0.5.0


18
19
20
21
22
# File 'lib/typhoeus/cache/redis.rb', line 18

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


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

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