Module: Sequel::Plugins::Caching

Defined in:
lib/sequel/plugins/caching.rb

Overview

Sequel’s built-in caching plugin supports caching to any object that implements the Ruby-Memcache API (or memcached API with the :ignore_exceptions option):

cache_store.set(key, obj, time) # Associate the obj with the given key
                                # in the cache for the time (specified
                                # in seconds).
cache_store.get(key) # => obj   # Returns object set with same key.
cache_store.get(key2) # => nil  # nil returned if there isn't an object
                                # currently in the cache with that key.
cache_store.delete(key)         # Remove key from cache

If the :ignore_exceptions option is true, exceptions raised by cache_store.get are ignored and nil is returned instead. The memcached API is to raise an exception for a missing record, so if you use memcached, you will want to use this option.

Note that only lookups by primary key are cached using this plugin. The following methods use a lookup by primary key:

  • Model.with_pk

  • Model.with_pk!

  • Model.[] # when argument is not hash or nil

  • many_to_one association method # without dynamic callback, when primary key matches

You should not use this plugin if you are using sharding and there are different rows for the same primary key on different shards.

Usage:

# Make all subclasses use the same cache (called before loading subclasses)
# using the Ruby-Memcache API, with the cache stored in the CACHE constant
Sequel::Model.plugin :caching, CACHE

# Make the Album class use the cache with a 30 minute time-to-live
Album.plugin :caching, CACHE, ttl: 1800

# Make the Artist class use a cache with the memcached protocol
Artist.plugin :caching, MEMCACHED_CACHE, ignore_exceptions: true

Defined Under Namespace

Modules: ClassMethods, InstanceMethods

Class Method Summary collapse

Class Method Details

.configure(model, store, opts = OPTS) ⇒ Object

Set the cache_store and cache_ttl attributes for the given model. If the :ttl option is not given, 3600 seconds is the default.



47
48
49
50
51
52
53
# File 'lib/sequel/plugins/caching.rb', line 47

def self.configure(model, store, opts=OPTS)
  model.instance_exec do
    @cache_store = store
    @cache_ttl = opts[:ttl] || 3600
    @cache_ignore_exceptions = opts[:ignore_exceptions]
  end
end