Module: ActionController::Caching::Fragments

### Home Classes Methods

### In Files

- lib/action_controller/caching/fragments.rb

### Methods

- #expire_fragment
- #fragment_cache_key
- #fragment_exist?
- #instrument_fragment_cache
- #read_fragment
- #write_fragment

### Class/Module Index

Quicksearch

- ActionDispatch
- ActionDispatch::Assertions
- ActionDispatch::Assertions::DomAssertions
- ActionDispatch::Assertions::ResponseAssertions
- ActionDispatch::Assertions::RoutingAssertions
- ActionDispatch::Assertions::SelectorAssertions
- ActionDispatch::Assertions::TagAssertions
- ActionDispatch::BestStandardsSupport
- ActionDispatch::BodyProxy
- ActionDispatch::Callbacks
- ActionDispatch::Cookies
- ActionDispatch::Cookies::CookieOverflow
- ActionDispatch::DebugExceptions
- ActionDispatch::ExceptionWrapper
- ActionDispatch::FileHandler
- ActionDispatch::Flash
- ActionDispatch::Flash::FlashHash
- ActionDispatch::Head
- ActionDispatch::Http
- ActionDispatch::Http::Cache
- ActionDispatch::Http::Cache::Request
- ActionDispatch::Http::Cache::Response
- ActionDispatch::Http::FilterParameters
- ActionDispatch::Http::Headers
- ActionDispatch::Http::MimeNegotiation
- ActionDispatch::Http::ParameterFilter
- ActionDispatch::Http::Parameters
- ActionDispatch::Http::URL
- ActionDispatch::Http::Upload
- ActionDispatch::Http::UploadedFile
- ActionDispatch::Integration
- ActionDispatch::Integration::RequestHelpers
- ActionDispatch::Integration::Runner
- ActionDispatch::Integration::Session
- ActionDispatch::IntegrationTest
- ActionDispatch::MiddlewareStack
- ActionDispatch::MiddlewareStack::Middleware
- ActionDispatch::ParamsParser
- ActionDispatch::PerformanceTest
- ActionDispatch::PublicExceptions
- ActionDispatch::RailsEntityStore
- ActionDispatch::RailsMetaStore
- ActionDispatch::Railtie
- ActionDispatch::Reloader
- ActionDispatch::RemoteIp
- ActionDispatch::RemoteIp::GetIp
- ActionDispatch::RemoteIp::IpSpoofAttackError
- ActionDispatch::Request
- ActionDispatch::RequestId
- ActionDispatch::Rescue
- ActionDispatch::Response
- ActionDispatch::Routing
- ActionDispatch::Routing::Mapper
- ActionDispatch::Routing::Mapper::Base
- ActionDispatch::Routing::Mapper::HttpHelpers
- ActionDispatch::Routing::Mapper::Resources
- ActionDispatch::Routing::Mapper::Scoping
- ActionDispatch::Routing::PolymorphicRoutes
- ActionDispatch::Routing::Redirection
- ActionDispatch::Routing::RouteSet
- ActionDispatch::Routing::RouteSet::MountedHelpers
- ActionDispatch::Routing::UrlFor
- ActionDispatch::Session
- ActionDispatch::Session::AbstractStore
- ActionDispatch::Session::CacheStore
- ActionDispatch::Session::Compatibility
- ActionDispatch::Session::CookieStore
- ActionDispatch::Session::DestroyableSession
- ActionDispatch::Session::MemCacheStore
- ActionDispatch::Session::StaleSessionCheck
- ActionDispatch::ShowExceptions
- ActionDispatch::Static
- ActionDispatch::TestProcess
- ActionDispatch::TestRequest
- ActionDispatch::TestResponse
- ActionController
- ActionController::Base
- ActionController::Caching
- ActionController::Caching::Actions
- ActionController::Caching::Actions::ActionCachePath
- ActionController::Caching::Actions::ClassMethods
- ActionController::Caching::ConfigMethods
- ActionController::Caching::Fragments
- ActionController::Caching::Pages
- ActionController::Caching::Pages::ClassMethods
- ActionController::Caching::Sweeping
- ActionController::Compatibility
- ActionController::ConditionalGet
- ActionController::Cookies
- ActionController::DataStreaming
- ActionController::Flash
- ActionController::ForceSSL
- ActionController::ForceSSL::ClassMethods
- ActionController::Head
- ActionController::Helpers
- ActionController::Helpers::ClassMethods
- ActionController::HideActions
- ActionController::HideActions::ClassMethods
- ActionController::HttpAuthentication
- ActionController::HttpAuthentication::Basic
- ActionController::HttpAuthentication::Basic::ControllerMethods
- ActionController::HttpAuthentication::Basic::ControllerMethods::ClassMethods
- ActionController::HttpAuthentication::Digest
- ActionController::HttpAuthentication::Digest::ControllerMethods
- ActionController::HttpAuthentication::Token
- ActionController::HttpAuthentication::Token::ControllerMethods
- ActionController::ImplicitRender
- ActionController::Instrumentation
- ActionController::Instrumentation::ClassMethods
- ActionController::LogSubscriber
- ActionController::Metal
- ActionController::Middleware
- ActionController::Middleware::ActionMiddleware
- ActionController::MimeResponds
- ActionController::MimeResponds::ClassMethods
- ActionController::ParamsWrapper
- ActionController::ParamsWrapper::ClassMethods
- ActionController::RackDelegation
- ActionController::Railtie
- ActionController::Railties
- ActionController::Railties::Paths
- ActionController::RecordIdentifier
- ActionController::Redirecting
- ActionController::Renderers
- ActionController::Renderers::All
- ActionController::Renderers::ClassMethods
- ActionController::Rendering
- ActionController::RequestForgeryProtection
- ActionController::RequestForgeryProtection::ClassMethods
- ActionController::Rescue
- ActionController::Responder
- ActionController::SessionManagement
- ActionController::SessionManagement::ClassMethods
- ActionController::Streaming
- ActionController::TemplateAssertions
- ActionController::TestCase
- ActionController::TestCase::Behavior
- ActionController::TestCase::Behavior::ClassMethods
- ActionController::TestCase::RaiseActionExceptions
- ActionController::TestResponse
- ActionController::Testing
- ActionController::Testing::ClassMethods
- ActionController::UrlFor
- ActionView
- ActionView::Base
- ActionView::Context
- ActionView::FileSystemResolver
- ActionView::FixtureResolver
- ActionView::Helpers
- ActionView::Helpers::ActiveModelHelper
- ActionView::Helpers::ActiveModelInstanceTag
- ActionView::Helpers::AssetPaths
- ActionView::Helpers::AssetTagHelper
- ActionView::Helpers::AssetTagHelper::AssetIncludeTag
- ActionView::Helpers::AssetTagHelper::JavascriptIncludeTag
- ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers
- ActionView::Helpers::AssetTagHelper::JavascriptTagHelpers::ClassMethods
- ActionView::Helpers::AssetTagHelper::StylesheetIncludeTag
- ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers
- ActionView::Helpers::AssetTagHelper::StylesheetTagHelpers::ClassMethods
- ActionView::Helpers::AtomFeedHelper
- ActionView::Helpers::AtomFeedHelper::AtomBuilder
- ActionView::Helpers::AtomFeedHelper::AtomFeedBuilder
- ActionView::Helpers::CacheHelper
- ActionView::Helpers::CaptureHelper
- ActionView::Helpers::CsrfHelper
- ActionView::Helpers::DateHelper
- ActionView::Helpers::DateHelperInstanceTag
- ActionView::Helpers::DebugHelper
- ActionView::Helpers::FormBuilder
- ActionView::Helpers::FormHelper
- ActionView::Helpers::FormOptionsHelper
- ActionView::Helpers::FormTagHelper
- ActionView::Helpers::InstanceTag
- ActionView::Helpers::JavaScriptHelper
- ActionView::Helpers::OutputSafetyHelper
- ActionView::Helpers::RecordTagHelper
- ActionView::Helpers::RenderingHelper
- ActionView::Helpers::SanitizeHelper
- ActionView::Helpers::TagHelper
- ActionView::Helpers::TextHelper
- ActionView::Helpers::TranslationHelper
- ActionView::Helpers::UrlHelper
- ActionView::LogSubscriber
- ActionView::LookupContext
- ActionView::LookupContext::DetailsCache
- ActionView::LookupContext::ViewPaths
- ActionView::NullResolver
- ActionView::PartialRenderer
- ActionView::Railtie
- ActionView::Renderer
- ActionView::Resolver
- ActionView::Resolver::Path
- ActionView::Template
- ActionView::Template::Handlers
- ActionView::Template::Handlers::Builder
- ActionView::Template::Handlers::ERB
- ActionView::Template::Handlers::Erubis
- ActionView::TestCase
- ActionView::TestCase::Behavior
- ActionView::TestCase::Behavior::ClassMethods
- ActionView::TestCase::Behavior::Locals
- ActionView::TestCase::TestController
- AbstractController
- AbstractController::ActionNotFound
- AbstractController::AssetPaths
- AbstractController::Base
- AbstractController::Callbacks
- AbstractController::Callbacks::ClassMethods
- AbstractController::Collector
- AbstractController::DoubleRenderError
- AbstractController::Error
- AbstractController::Helpers
- AbstractController::Helpers::ClassMethods
- AbstractController::Layouts
- AbstractController::Layouts::ClassMethods
- AbstractController::Layouts::ClassMethods::LayoutConditions
- AbstractController::Logger
- AbstractController::Railties
- AbstractController::Railties::RoutesHelpers
- AbstractController::Rendering
- AbstractController::Rendering::ClassMethods
- AbstractController::Translation
- AbstractController::UrlFor
- AbstractController::UrlFor::ClassMethods
- AbstractController::ViewPaths
- AbstractController::ViewPaths::ClassMethods
- Sprockets
- Sprockets::Bootstrap
- Sprockets::Compressors
- Sprockets::Helpers
- Sprockets::Helpers::IsolatedHelper
- Sprockets::Helpers::RailsHelper
- Sprockets::Helpers::RailsHelper::AssetPaths
- Sprockets::Helpers::RailsHelper::AssetPaths::AssetNotPrecompiledError
- Sprockets::Railtie
- Sprockets::StaticCompiler
- HTML
- HTML::FullSanitizer
- HTML::LinkSanitizer
- HTML::Sanitizer
- HTML::Selector
- HTML::Tag
- HTML::WhiteListSanitizer
- Mime
- Mime::Mimes
- Mime::Type
- ActionPack
- Object
- Rack

No matching classes.

# ActionController::Caching::Fragments

Fragment caching is used for caching various blocks within views without caching the entire action as a whole. This is useful when certain elements of an action change frequently or depend on complicated state while other parts rarely change or can be shared amongst multiple parties. The caching is done using the `cache` helper available in the Action View. A template with fragment caching might look like:

    <b>Hello <%= @name %></b>

    <% cache do %>
      All the topics in the system:
      <%= render :partial => "topic", :collection => Topic.all %>
    <% end %>

This cache will bind the name of the action that called it, so if this code was part of the view for the topics/list action, you would be able to invalidate it using:

    expire_fragment(:controller => "topics", :action => "list")

This default behavior is limited if you need to cache multiple fragments per action or if the action itself is cached using `caches_action`. To remedy this, there is an option to qualify the name of the cached fragment by using the `:action_suffix` option:

    <% cache(:action => "list", :action_suffix => "all_topics") do %>

That would result in a name such as `/topics/list/all_topics`, avoiding conflicts with the action cache and with any fragments that use a different suffix. Note that the URL doesn't have to really exist or be callable

- the url_for system is just used to generate unique cache names

that we can refer to when we need to expire the cache.

The expiration call for this example is:

    expire_fragment(:controller => "topics",
                    :action => "list",
                    :action_suffix => "all_topics")

### Public Instance Methods

expire_fragment(key, options = nil) click to toggle source

Removes fragments from the cache.

`key` can take one of three forms:

- String - This would normally take the form of a path, like `pages/45/notes`.

- Hash - Treated as an implicit call to `url_for`, like `{:controller => "pages", :action => "notes", :id => 45}`

- Regexp - Will remove any fragment that matches, so `%r{pages/\d*/notes}` might remove all notes. Make sure you don't use anchors in the regex (`^` or `$`) because the actual filename matched looks like `./cache/filename/path.cache`. Note: Regexp expiration is only supported on caches that can iterate over all keys (unlike memcached).

`options` is passed through to the cache store's `delete` method (or `delete_matched`, for Regexp keys.)

    # File lib/action_controller/caching/fragments.rb, line 109
    def expire_fragment(key, options = nil)
      return unless cache_configured?
      key = fragment_cache_key(key) unless key.is_a?(Regexp)

      instrument_fragment_cache :expire_fragment, key do
        if key.is_a?(Regexp)
          cache_store.delete_matched(key, options)
        else
          cache_store.delete(key, options)
        end
      end
    end

fragment_cache_key(key) click to toggle source

Given a key (as described in `expire_fragment`), returns a key suitable for use in reading, writing, or expiring a cached fragment. If the key is a hash, the generated key is the return value of url_for on that hash (without the protocol). All keys are prefixed with `views/` and uses ActiveSupport::Cache.expand_cache_key for the expansion.

    # File lib/action_controller/caching/fragments.rb, line 51
    def fragment_cache_key(key)
      ActiveSupport::Cache.expand_cache_key(key.is_a?(Hash) ? url_for(key).split("://").last : key, :views)
    end

fragment_exist?(key, options = nil) click to toggle source

Check if a cached fragment from the location signified by `key` exists (see `expire_fragment` for acceptable formats)

    # File lib/action_controller/caching/fragments.rb, line 82
    def fragment_exist?(key, options = nil)
      return unless cache_configured?
      key = fragment_cache_key(key)

      instrument_fragment_cache :exist_fragment?, key do
        cache_store.exist?(key, options)
      end
    end

instrument_fragment_cache(name, key) click to toggle source

    # File lib/action_controller/caching/fragments.rb, line 122
    def instrument_fragment_cache(name, key)
      ActiveSupport::Notifications.instrument("#{name}.action_controller", :key => key){ yield }
    end

read_fragment(key, options = nil) click to toggle source

Reads a cached fragment from the location signified by `key` (see `expire_fragment` for acceptable formats).

    # File lib/action_controller/caching/fragments.rb, line 70
    def read_fragment(key, options = nil)
      return unless cache_configured?

      key = fragment_cache_key(key)
      instrument_fragment_cache :read_fragment, key do
        result = cache_store.read(key, options)
        result.respond_to?(:html_safe) ? result.html_safe : result
      end
    end

write_fragment(key, content, options = nil) click to toggle source

Writes `content` to the location signified by `key` (see `expire_fragment` for acceptable formats).

    # File lib/action_controller/caching/fragments.rb, line 57
    def write_fragment(key, content, options = nil)
      return content unless cache_configured?

      key = fragment_cache_key(key)
      instrument_fragment_cache :write_fragment, key do
        content = content.to_str
        cache_store.write(key, content, options)
      end
      content
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.