Module: Padrino::Cache::Helpers::Fragment

Includes:
Helpers::OutputHelpers
Defined in:
padrino-cache/lib/padrino-cache/helpers/fragment.rb

Overview

Whereas page-level caching, described in the first section of this document, works by grabbing the entire output of a route, fragment caching gives the developer fine-grained control of what gets cached. This type of caching occurs at whatever level you choose.

Possible uses for fragment caching might include:

  • a 'feed' of some items on a page

  • output fetched (by proxy) from an API on a third-party site

  • parts of your page which are largely static/do not need re-rendering every request

  • any output which is expensive to render

Instance Method Summary collapse

Methods included from Helpers::OutputHelpers

#block_is_template?, #capture_html, #concat_content, #concat_safe_content, #content_for, #content_for?, handlers, register, #yield_content

Instance Method Details

#cache(key, opts = {}, &block) ⇒ Object

This helper is used anywhere in your application you would like to associate a fragment to be cached. It can be used in within a route:

Examples:

# Caching a fragment
class MyTweets < Padrino::Application
  enable :caching          # turns on caching mechanism

  controller '/tweets' do
    get :feed, :map => '/:username' do
      username = params[:username]

      @feed = cache( "feed_for_#{username}", :expires => 3 ) do
        @tweets = Tweet.all( :username => username )
        render 'partials/feedcontent'
      end

      # Below outputs @feed somewhere in its markup.
      render 'feeds/show'
    end
  end
end

Parameters:

  • key (String)

    cache key

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

    cache options, e.g :expires

  • Execution (Proc)

    result to store in the cache



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'padrino-cache/lib/padrino-cache/helpers/fragment.rb', line 51

def cache(key, opts = {}, &block)
  if settings.caching?
    began_at = Time.now
    if settings.cache.key?(key.to_s)
      value = settings.cache[key.to_s]
      logger.debug "GET Fragment", began_at, key.to_s if defined?(logger)
      concat_content(value.to_s.html_safe)
    else
      value = capture_html(&block)
      settings.cache.store(key.to_s, value, opts)
      logger.debug "SET Fragment", began_at, key.to_s if defined?(logger)
      concat_content(value)
    end
  else
    value = capture_html(&block)
    concat_content(value)
  end
end