### Home Classes Methods

### In Files

- lib/merb-core/controller/mixins/controller.rb

### Methods

- #delete_cookie
- #escape_html
- #escape_xml
- #h
- #message
- #nginx_send_file
- #redirect
- #render_chunked
- #render_deferred
- #render_then_call
- #run_later
- #send_chunk
- #send_data
- #send_file
- #set_cookie
- #stream_file

### Files

- CHANGELOG
- LICENSE
- README
- TODO

### Class/Module Index

Quicksearch

- Merb
- Merb::AbstractController
- Merb::AcceptType
- Merb::AuthenticationMixin
- Merb::AuthenticationMixin::BasicAuthentication
- Merb::BootLoader
- Merb::BootLoader::AfterAppLoads
- Merb::BootLoader::BackgroundServices
- Merb::BootLoader::BeforeAppLoads
- Merb::BootLoader::BuildFramework
- Merb::BootLoader::ChooseAdapter
- Merb::BootLoader::Cookies
- Merb::BootLoader::Defaults
- Merb::BootLoader::Dependencies
- Merb::BootLoader::DropPidFile
- Merb::BootLoader::LoadClasses
- Merb::BootLoader::Logger
- Merb::BootLoader::MimeTypes
- Merb::BootLoader::MixinSession
- Merb::BootLoader::RackUpApplication
- Merb::BootLoader::ReloadClasses
- Merb::BootLoader::ReloadClasses::TimedExecutor
- Merb::BootLoader::Router
- Merb::BootLoader::SetupSession
- Merb::BootLoader::SetupStubClasses
- Merb::BootLoader::Templates
- Merb::ConditionalGetMixin
- Merb::Config
- Merb::Config::ConfigBlock
- Merb::Const
- Merb::Controller
- Merb::ControllerExceptions
- Merb::ControllerExceptions::Accepted
- Merb::ControllerExceptions::ActionNotFound
- Merb::ControllerExceptions::BadGateway
- Merb::ControllerExceptions::BadRequest
- Merb::ControllerExceptions::Base
- Merb::ControllerExceptions::ClientError
- Merb::ControllerExceptions::Conflict
- Merb::ControllerExceptions::Continue
- Merb::ControllerExceptions::Created
- Merb::ControllerExceptions::ExpectationFailed
- Merb::ControllerExceptions::Forbidden
- Merb::ControllerExceptions::GatewayTimeout
- Merb::ControllerExceptions::Gone
- Merb::ControllerExceptions::HTTPVersionNotSupported
- Merb::ControllerExceptions::Informational
- Merb::ControllerExceptions::InternalServerError
- Merb::ControllerExceptions::LayoutNotFound
- Merb::ControllerExceptions::LengthRequired
- Merb::ControllerExceptions::MethodNotAllowed
- Merb::ControllerExceptions::MovedPermanently
- Merb::ControllerExceptions::MovedTemporarily
- Merb::ControllerExceptions::MultiPartParseError
- Merb::ControllerExceptions::MultipleChoices
- Merb::ControllerExceptions::NoContent
- Merb::ControllerExceptions::NonAuthoritativeInformation
- Merb::ControllerExceptions::NotAcceptable
- Merb::ControllerExceptions::NotFound
- Merb::ControllerExceptions::NotImplemented
- Merb::ControllerExceptions::NotModified
- Merb::ControllerExceptions::OK
- Merb::ControllerExceptions::PartialContent
- Merb::ControllerExceptions::PaymentRequired
- Merb::ControllerExceptions::PreconditionFailed
- Merb::ControllerExceptions::ProxyAuthenticationRequired
- Merb::ControllerExceptions::Redirection
- Merb::ControllerExceptions::RequestEntityTooLarge
- Merb::ControllerExceptions::RequestRangeNotSatisfiable
- Merb::ControllerExceptions::RequestTimeout
- Merb::ControllerExceptions::RequestURITooLarge
- Merb::ControllerExceptions::ResetContent
- Merb::ControllerExceptions::SeeOther
- Merb::ControllerExceptions::ServerError
- Merb::ControllerExceptions::ServiceUnavailable
- Merb::ControllerExceptions::Successful
- Merb::ControllerExceptions::SwitchingProtocols
- Merb::ControllerExceptions::TemplateNotFound
- Merb::ControllerExceptions::TemporaryRedirect
- Merb::ControllerExceptions::Unauthorized
- Merb::ControllerExceptions::UnsupportedMediaType
- Merb::ControllerExceptions::UseProxy
- Merb::ControllerMixin
- Merb::CookieSession
- Merb::CookieSession::CookieOverflow
- Merb::CookieSession::TamperedWithCookie
- Merb::Cookies
- Merb::CookiesMixin
- Merb::CookiesMixin::RequestMixin
- Merb::Counter
- Merb::Dispatcher
- Merb::Dispatcher::DefaultException
- Merb::Dispatcher::DefaultExceptionHelper
- Merb::GlobalHelpers
- Merb::InlineTemplates
- Merb::Logger
- Merb::MemcacheSession
- Merb::MemcacheStore
- Merb::MemorySession
- Merb::MemorySessionStore
- Merb::Parse
- Merb::Plugins
- Merb::Rack
- Merb::Rack::AbstractAdapter
- Merb::Rack::Adapter
- Merb::Rack::Application
- Merb::Rack::ConditionalGet
- Merb::Rack::Console
- Merb::Rack::ContentLength
- Merb::Rack::DeferrableMiddleware
- Merb::Rack::Ebb
- Merb::Rack::EventedMongrel
- Merb::Rack::FastCGI
- Merb::Rack::Handler
- Merb::Rack::Handler::Mongrel
- Merb::Rack::Head
- Merb::Rack::Helpers
- Merb::Rack::Irb
- Merb::Rack::Middleware
- Merb::Rack::Mongrel
- Merb::Rack::PathPrefix
- Merb::Rack::Profiler
- Merb::Rack::Runner
- Merb::Rack::Static
- Merb::Rack::StreamWrapper
- Merb::Rack::SwiftipliedMongrel
- Merb::Rack::Thin
- Merb::Rack::ThinTurbo
- Merb::Rack::Tracer
- Merb::Rack::WEBrick
- Merb::RenderMixin
- Merb::RenderMixin::ClassMethods
- Merb::Request
- Merb::ReservedError
- Merb::Responder
- Merb::ResponderMixin
- Merb::ResponderMixin::ClassMethods
- Merb::ResponderMixin::ContentTypeAlreadySet
- Merb::Router
- Merb::Router::Behavior
- Merb::Router::Behavior::Error
- Merb::Router::Behavior::Proxy
- Merb::Router::CachedProc
- Merb::Router::GenerationError
- Merb::Router::NotCompiledError
- Merb::Router::Resources
- Merb::Router::RouteNotFound
- Merb::Server
- Merb::Session
- Merb::SessionContainer
- Merb::SessionMixin
- Merb::SessionMixin::NoSessionContainer
- Merb::SessionMixin::RequestMixin
- Merb::SessionMixin::RequestMixin::ClassMethods
- Merb::SessionMixin::SessionOverflow
- Merb::SessionStoreContainer
- Merb::System
- Merb::System::PortablePoller
- Merb::Template
- Merb::Template::Erubis
- Merb::Template::Erubis::Mixin
- Merb::Test
- Merb::Test::ControllerHelper
- Merb::Test::Cookie
- Merb::Test::CookieJar
- Merb::Test::ExampleGroup
- Merb::Test::Helpers
- Merb::Test::MakeRequest
- Merb::Test::Matchers
- Merb::Test::MultipartRequestHelper
- Merb::Test::MultipartRequestHelper::FileParam
- Merb::Test::MultipartRequestHelper::Param
- Merb::Test::MultipartRequestHelper::Post
- Merb::Test::RequestHelper
- Merb::Test::RequestHelper::CookieJar
- Merb::Test::RequestHelper::FakeRequest
- Merb::Test::RouteHelper
- Merb::Test::Rspec
- Merb::Test::Rspec::ControllerMatchers
- Merb::Test::Rspec::ControllerMatchers::BeError
- Merb::Test::Rspec::ControllerMatchers::BeRedirect
- Merb::Test::Rspec::ControllerMatchers::Provide
- Merb::Test::Rspec::RouteMatchers
- Merb::Test::Rspec::RouteMatchers::ParameterMatcher
- Merb::Test::Rspec::RouteMatchers::RouteToMatcher
- Merb::Test::ViewHelper
- Merb::Test::WebratHelper
- Merb::Worker
- Erubis
- Erubis::Basic
- Erubis::Basic::Converter
- Erubis::BlockAwareEnhancer
- Erubis::BlockAwareEruby
- Erubis::MEruby
- Spec
- Spec::Matchers
- Spec::Matchers::MatcherDSL
- Spec::Runner
- Spec::Runner::Formatter
- Spec::Runner::Formatter::BaseTextFormatter
- Gem
- Gem::Dependency
- Hpricot
- Hpricot::Elem
- Mongrel
- Mongrel::HttpResponse
- Class
- Exception
- Hash
- Kernel
- MemCache
- Memcached
- Object
- String
- Time

No matching classes.

# Merb::ControllerMixin

Module that is mixed in to all implemented controllers.

### Public Instance Methods

delete_cookie(name) click to toggle source

Marks a cookie as deleted and gives it an expires stamp in the past. This method is used primarily internally in Merb.

Use the `cookies` hash to manipulate cookies instead.

#### Parameters

name<~to_s> | A name for the cookie to delete.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 328
    def delete_cookie(name)
      set_cookie(name, nil, Merb::Const::COOKIE_EXPIRED_TIME)
    end

escape_html(obj) click to toggle source
Alias for: escape_xml
escape_xml(obj) click to toggle source

Escapes the string representation of `obj` and escapes it for use in XML.

#### Parameter

obj<~to_s> | The object to escape for use in XML.

#### Returns

String | The escaped object.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 341
    def escape_xml(obj)
      Merb::Parse.escape_xml(obj.to_s)
    end

Also aliased as: h, escape_html
h(obj) click to toggle source
Alias for: escape_xml
message() click to toggle source

Retreives the redirect message either locally or from the request.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 161
    def message
      @_message = defined?(@_message) ? @_message : request.message
    end

nginx_send_file(path, content_type = "") click to toggle source

Uses the nginx specific `X-Accel-Redirect` header to send a file directly from nginx.

#### Notes

Unless Content-Disposition is set before calling this method, it is set to attachment with streamed file name.

For more information, see the nginx wiki: wiki.codemongers.com/NginxXSendfile

and the following sample gist: gist.github.com/11225

there's also example application up on GitHub:

github.com/michaelklishin/nginx-x-accel-redirect-example-application/tree/master

#### Parameters

path<String> | Path to file to send to the client.
content_type<String> | content type header value. By default is set to empty string to let Nginx detect it.

#### Return

String | precisely a single space.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 294
    def nginx_send_file(path, content_type = "")
      # Let Nginx detect content type unless it is explicitly set
      headers['Content-Type']        = content_type
      headers["Content-Disposition"] ||= "attachment; filename=#{path.split('/').last}"

      headers['X-Accel-Redirect']    = path

      return ' '
    end

redirect(url, opts = {}) click to toggle source

#### Parameters

url<String> | URL to redirect to. It can be either a relative or fully-qualified URL.
opts<Hash> | An options hash (see below)

#### Options (opts)

:message<Hash> | Messages to pass in url query string as value for "_message"
:permanent<Boolean> | When true, return status 301 Moved Permanently
:notice<String> | Shorthand for common usage :message => {:notice => "..."}
:error<String> | Shorthand for common usage :message => {:error => "..."}
:success<String> | Shorthand for common usage :message => {:success => "..."}
:status<String, Symbol> | Status code to set for the response. Can be any valid redirect status. Has precedence over the :permanent parameter, which is retained for convenience.

#### Returns

String | Explanation of redirect.

#### Examples

    redirect("/posts/34")
    redirect("/posts/34", :message => { :notice => 'Post updated successfully!' })
    redirect("http://www.merbivore.com/")
    redirect("http://www.merbivore.com/", :permanent => true)
    redirect("/posts/34", :notice => 'Post updated successfully!')

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 143
    def redirect(url, opts = {})
      default_redirect_options = { :message => nil, :permanent => false }
      opts = default_redirect_options.merge(opts)

      url = handle_redirect_messages(url,opts)

      _status   = opts[:status] if opts[:status]
      _status ||= opts[:permanent] ? 301 : 302
      self.status = _status

      Merb.logger.info("Redirecting to: #{url} (#{self.status})")
      headers['Location'] = url
      "<html><body>You are being <a href=\"#{url}\">redirected</a>.</body></html>"
    end

render_chunked(&blk) click to toggle source

Renders the block given as a parameter using chunked encoding.

#### Parameters

&blk | A block that, when called, will use send_chunks to send chunks of data down to the server. The chunking will terminate once the block returns.

#### Examples

    def stream
      prefix = '<p>'
      suffix = "</p>\r\n"
      render_chunked do
        IO.popen("cat /tmp/test.log") do |io|
          done = false
          until done
            sleep 0.3
            line = io.gets.chomp

            if line == 'EOF'
              done = true
            else
              send_chunk(prefix + line + suffix)
            end
          end
        end
      end
    end

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 50
    def render_chunked(&blk)
      must_support_streaming!
      headers['Transfer-Encoding'] = 'chunked'
      Proc.new { |response|
        @response = response
        response.send_status_no_connection_close('')
        response.send_header
        blk.call
        response.write("0\r\n\r\n")
      }
    end

render_deferred(&blk) click to toggle source

#### Parameters

&blk | A proc that should get called outside the mutex, and which will return the value to render.

#### Returns

Proc | A block that the server can call later, allowing Merb to release the thread lock and render another request.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 86
    def render_deferred(&blk)
      Proc.new do |response|
        response.write(blk.call)
      end
    end

render_then_call(str, &blk) click to toggle source

Renders the passed in string, then calls the block outside the mutex and after the string has been returned to the client.

#### Parameters

str<String> | A `String` to return to the client.
&blk | A block that should get called once the string has been returned.

#### Returns

Proc | A block that Mongrel can call after returning the string to the user.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 104
    def render_then_call(str, &blk)
      Proc.new do |response|
        response.write(str)
        blk.call
      end
    end

run_later(&blk) click to toggle source

Enqueu a block to run in a background thread outside of the request response dispatch

#### Parameters

&blk | proc to run later

#### Example

run_later do

    SomeBackgroundTask.run

end

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 17
    def run_later(&blk)
      Merb.run_later(&blk)
    end

send_chunk(data) click to toggle source

Writes a chunk from `render_chunked` to the response that is sent back to the client. This should only be called within a `render_chunked` block.

#### Parameters

data<String> | a chunk of data to return.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 69
    def send_chunk(data)
      only_runs_on_mongrel!
      @response.write('%x' % data.size + "\r\n")
      @response.write(data + "\r\n")
    end

send_data(data, opts={}) click to toggle source

Send binary data over HTTP to the user as a file download. May set content type, apparent file name, and specify whether to show data inline or download as an attachment.

#### Parameters

data<String> | Path to file to send to the client.
opts<Hash> | Options for sending the data (see below).

#### Options (opts)

:disposition<String> | The disposition of the file send. Defaults to "attachment".
:filename<String> | The name to use for the file. Defaults to the filename of file.
:type<String> | The content type.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 216
    def send_data(data, opts={})
      opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))
      disposition = opts[:disposition].dup || 'attachment'
      disposition << %(; filename="#{opts[:filename]}") if opts[:filename]
      headers.update(
        'Content-Type'              => opts[:type].strip,  # fixes a problem with extra '\r' with some browsers
        'Content-Disposition'       => disposition,
        'Content-Transfer-Encoding' => 'binary'
      )
      data
    end

send_file(file, opts={}) click to toggle source

Sends a file over HTTP. When given a path to a file, it will set the right headers so that the static file is served directly.

#### Parameters

file<String> | Path to file to send to the client.
opts<Hash> | Options for sending the file (see below).

#### Options (opts)

:disposition<String> | The disposition of the file send. Defaults to "attachment".
:filename<String> | The name to use for the file. Defaults to the filename of file.
:type<String> | The content type.

#### Returns

IO | An I/O stream for the file.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 183
    def send_file(file, opts={})
      opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))
      disposition = opts[:disposition].dup || 'attachment'
      disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}")
      headers.update(
        'Content-Type'              => opts[:type].strip,  # fixes a problem with extra '\r' with some browsers
        'Content-Disposition'       => disposition,
        'Content-Transfer-Encoding' => 'binary'
      )
      Proc.new do |response|
        file = File.open(file, 'rb')
        while chunk = file.read(16384)
          response.write chunk
        end
        file.close
      end
    end

set_cookie(name, value, expires) click to toggle source

Sets a cookie to be included in the response.

If you need to set a cookie, then use the `cookies` hash.

#### Parameters

name<~to_s> | A name for the cookie.
value<~to_s> | A value for the cookie.
expires<~gmtime:~strftime, Hash> | An expiration time for the cookie, or a hash of cookie options.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 314
    def set_cookie(name, value, expires)
      options = expires.is_a?(Hash) ? expires : {:expires => expires}
      cookies.set_cookie(name, value, options)
    end

stream_file(opts={}, &stream) click to toggle source

Streams a file over HTTP.

#### Parameters

opts<Hash> | Options for the file streaming (see below).
&stream | A block that, when called, will return an object that responds to `get_lines` for streaming.

#### Options

:disposition<String> | The disposition of the file send. Defaults to "attachment".
:type<String> | The content type.
:content_length<Numeric> | The length of the content to send.
:filename<String> | The name to use for the streamed file.

#### Examples

    stream_file({ :filename => file_name, :type => content_type,
      :content_length => content_length }) do |response|
      AWS::S3::S3Object.stream(user.folder_name + "-" + user_file.unique_id, bucket_name) do |chunk|
        response.write chunk
      end
    end

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 252
    def stream_file(opts={}, &stream)
      opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))
      disposition = opts[:disposition].dup || 'attachment'
      disposition << %(; filename="#{opts[:filename]}")
      headers.update(
        'Content-Type'              => opts[:type].strip,  # fixes a problem with extra '\r' with some browsers
        'Content-Disposition'       => disposition,
        'Content-Transfer-Encoding' => 'binary',
        # Rack specification requires header values to respond to :each
        'CONTENT-LENGTH'            => opts[:content_length].to_s
      )
      Proc.new do |response|
        stream.call(response)
      end
    end

[Validate]

Generated with the Darkfish Rdoc Generator 2.