Class: Cachew::Adapter

Inherits:
Object
  • Object
show all
Defined in:
lib/cachew/adapter.rb

Overview

Base class for Cachew adapters.

Examples:

Building custom adapters


class Cachew::Redis < Cache::Adapter
  def initialize(client)
    @client = client
  end

  private

  def __set__(key, val, ttl)
    val = Marshal.dump val

    if 0 == ttl
      @client.set key, val
    else
      @client.setex key, val, ttl
    end
  end

  def __get__(key)
    val = @client.get(key)
    val ? Marshal.load(val) : UNDEFINED
  end

  def __key__(*)
    "cachew:#{super}"
  end
end

Direct Known Subclasses

Hash, Null

Constant Summary collapse

UNDEFINED =

Internal constant used by ‘__get__` to notify that value is not in the cache or became stale

Object.new.freeze

Instance Method Summary collapse

Instance Method Details

#fetch(key, opts = {}) ⇒ Object

Examples:

Usage


cachew.fetch "some_key", :ttl => 60 do
  HTTP.get("http://example.com").to_s
end


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

def fetch(key, opts = {})
  key = __key__ key, opts
  val = __get__ key

  if UNDEFINED.equal? val
    val = yield
    ttl = opts.fetch(:ttl) { 0 }.to_i

    __set__ key, val, ttl
  end

  val
end