Module: ActionController::Streaming

### Home Classes Methods

### In Files

- lib/action_controller/metal/streaming.rb

### Included Modules

- AbstractController::Rendering

### 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::Streaming

Allows views to be streamed back to the client as they are rendered.

The default way Rails renders views is by first rendering the template and then the layout. The response is sent to the client after the whole template is rendered, all queries are made, and the layout is processed.

Streaming inverts the rendering flow by rendering the layout first and streaming each part of the layout as they are processed. This allows the header of the HTML (which is usually in the layout) to be streamed back to client very quickly, allowing JavaScripts and stylesheets to be loaded earlier than usual.

This approach was introduced in Rails 3.1 and is still improving. Several Rack middlewares may not work and you need to be careful when streaming. Those points are going to be addressed soon.

In order to use streaming, you will need to use a Ruby version that supports fibers (fibers are supported since version 1.9.2 of the main Ruby implementation).

## Examples

Streaming can be added to a given template easily, all you need to do is to pass the :stream option.

    class PostsController
      def index
        @posts = Post.scoped
        render :stream => true
      end
    end

## When to use streaming

Streaming may be considered to be overkill for lightweight actions like `new` or `edit`. The real benefit of streaming is on expensive actions that, for example, do a lot of queries on the database.

In such actions, you want to delay queries execution as much as you can. For example, imagine the following `dashboard` action:

    def dashboard
      @posts = Post.all
      @pages = Page.all
      @articles = Article.all
    end

Most of the queries here are happening in the controller. In order to benefit from streaming you would want to rewrite it as:

    def dashboard
      # Allow lazy execution of the queries
      @posts = Post.scoped
      @pages = Page.scoped
      @articles = Article.scoped
      render :stream => true
    end

Notice that :stream only works with templates. Rendering :json or :xml with :stream won't work.

## Communication between layout and template

When streaming, rendering happens top-down instead of inside-out. Rails starts with the layout, and the template is rendered later, when its `yield` is reached.

This means that, if your application currently relies on instance variables set in the template to be used in the layout, they won't work once you move to streaming. The proper way to communicate between layout and template, regardless of whether you use streaming or not, is by using `content_for`, `provide` and `yield`.

Take a simple example where the layout expects the template to tell which title to use:

    <html>
      <head><title><%= yield :title %></title></head>
      <body><%= yield %></body>
    </html>

You would use `content_for` in your template to specify the title:

    <%= content_for :title, "Main" %>
    Hello

And the final result would be:

    <html>
      <head><title>Main</title></head>
      <body>Hello</body>
    </html>

However, if `content_for` is called several times, the final result would have all calls concatenated. For instance, if we have the following template:

    <%= content_for :title, "Main" %>
    Hello
    <%= content_for :title, " page" %>

The final result would be:

    <html>
      <head><title>Main page</title></head>
      <body>Hello</body>
    </html>

This means that, if you have `yield :title` in your layout and you want to use streaming, you would have to render the whole template (and eventually trigger all queries) before streaming the title and all assets, which kills the purpose of streaming. For this reason Rails 3.1 introduces a new helper called `provide` that does the same as `content_for` but tells the layout to stop searching for other entries and continue rendering.

For instance, the template above using `provide` would be:

    <%= provide :title, "Main" %>
    Hello
    <%= content_for :title, " page" %>

Giving:

    <html>
      <head><title>Main</title></head>
      <body>Hello</body>
    </html>

That said, when streaming, you need to properly check your templates and choose when to use `provide` and `content_for`.

## Headers, cookies, session and flash

When streaming, the HTTP headers are sent to the client right before it renders the first line. This means that, modifying headers, cookies, session or flash after the template starts rendering will not propagate to the client.

If you try to modify cookies, session or flash, an +ActionDispatch::ClosedError+ will be raised, showing those objects are closed for modification.

## Middlewares

Middlewares that need to manipulate the body won't work with streaming. You should disable those middlewares whenever streaming in development or production. For instance, +Rack::Bug+ won't work when streaming as it needs to inject contents in the HTML body.

Also +Rack::Cache+ won't work with streaming as it does not support streaming bodies yet. Whenever streaming Cache-Control is automatically set to "no-cache".

## Errors

When it comes to streaming, exceptions get a bit more complicated. This happens because part of the template was already rendered and streamed to the client, making it impossible to render a whole exception page.

Currently, when an exception happens in development or production, Rails will automatically stream to the client:

    "><script type="text/javascript">window.location = "/500.html"</script></html>

The first two characters (">) are required in case the exception happens while rendering attributes for a given tag. You can check the real cause for the exception in your logger.

## Web server support

Not all web servers support streaming out-of-the-box. You need to check the instructions for each of them.

#### Unicorn

Unicorn supports streaming but it needs to be configured. For this, you need to create a config file as follow:

    # unicorn.config.rb
    listen 3000, :tcp_nopush => false

And use it on initialization:

    unicorn_rails --config-file unicorn.config.rb

You may also want to configure other parameters like `:tcp_nodelay`. Please check its documentation for more information: unicorn.bogomips.org/Unicorn/Configurator.html#method-i-listen

If you are using Unicorn with Nginx, you may need to tweak Nginx. Streaming should work out of the box on Rainbows.

#### Passenger

To be described.

[Validate]

Generated with the Darkfish Rdoc Generator 2.