Module: Sinatra::SimpleCache

Defined in:
lib/sinatra/simplecache.rb,
lib/sinatra/simplecache/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#cache(opts = {}) { ... } ⇒ String

Returns Block evaluated value, or cached value.

Examples:

For operation cache:
 @@users = MySQL.query("...").to_a
 //=> @@users = cache(key: "users", expire: 0.6) { MySQL.query("...").to_a }

For page cache:
 slim: index
 //=> cache(expire: 0.3) {slim: index}

For fragment cache:
  @@sidebar = cache(key: "sidebar", expire: 1) { slim: sidebar }
  slim :detail, :locales = { :sidebar => @@sidebar }

Parameters:

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

    Must specified :key and :expire

Options Hash (opts):

  • :key (String)

    Cache key

  • :expire(Infinity) (Numeric)

    Expire time

Yields:

  • Evaluate template, RDB/KVS query etc

Returns:

  • (String)

    Block evaluated value, or cached value.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/sinatra/simplecache.rb', line 24

def cache(opts={}, &block)
  @@__entries__ ||= {}

  now = Time.now.to_f
  (expire = opts[:expire]) ? (expire + now) : (@@inf ||= 1/0.0)
  key = opts[:key] || (defined?(Sinatra) && request.path) || abort("set key")

  if (e = @@__entries__[key]) && (e[:expire] > now)
    return e[:value]
  end

  value = block.call
  @@__entries__[key] = {
    expire: expire,
    value: value
  }
  value
end