Class Index [+]

Quicksearch

Merb::ControllerMixin

Module that is mixed in to all implemented controllers.

Public Instance Methods

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
341:     def escape_xml(obj)
342:       Merb::Parse.escape_xml(obj.to_s)
343:     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
161:     def message
162:       @_message = defined?(@_message) ? @_message : request.message
163:     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

Path to file to send to the client.

content_type

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
294:     def nginx_send_file(path, content_type = "")
295:       # Let Nginx detect content type unless it is explicitly set
296:       headers['Content-Type']        = content_type
297:       headers["Content-Disposition"] ||= "attachment; filename=#{path.split('/').last}"
298:       
299:       headers['X-Accel-Redirect']    = path
300:       
301:       return ' '
302:     end
redirect(url, opts = {}) click to toggle source

Parameters

url

URL to redirect to. It can be either a relative or fully-qualified URL.

opts

An options hash (see below)

Options (opts)

:message

Messages to pass in url query string as value for “_message“

:permanent

When true, return status 301 Moved Permanently

:notice

Shorthand for common usage :message => {:notice => “…”}

:error

Shorthand for common usage :message => {:error => “…”}

:success

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
143:     def redirect(url, opts = {})
144:       default_redirect_options = { :message => nil, :permanent => false }
145:       opts = default_redirect_options.merge(opts)
146: 
147:       url = handle_redirect_messages(url,opts)
148: 
149:       _status   = opts[:status] if opts[:status]
150:       _status ||= opts[:permanent] ? 301 : 302
151:       self.status = _status
152: 
153:       Merb.logger.info("Redirecting to: #{url} (#{self.status})")
154:       headers['Location'] = url
155:       "<html><body>You are being <a href=\"#{url}\">redirected</a>.</body></html>"
156:     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
50:     def render_chunked(&blk)
51:       must_support_streaming!
52:       headers['Transfer-Encoding'] = 'chunked'
53:       Proc.new { |response|
54:         @response = response
55:         response.send_status_no_connection_close('')
56:         response.send_header
57:         blk.call
58:         response.write("0\r\n\r\n")
59:       }
60:     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
86:     def render_deferred(&blk)
87:       Proc.new do |response|
88:         response.write(blk.call)
89:       end
90:     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

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
104:     def render_then_call(str, &blk)
105:       Proc.new do |response|
106:         response.write(str)
107:         blk.call
108:       end
109:     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
17:     def run_later(&blk)
18:       Merb.run_later(&blk)
19:     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

a chunk of data to return.

:api: public

    # File lib/merb-core/controller/mixins/controller.rb, line 69
69:     def send_chunk(data)
70:       only_runs_on_mongrel!
71:       @response.write('%x' % data.size + "\r\n")
72:       @response.write(data + "\r\n")
73:     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

Path to file to send to the client.

opts

Options for sending the data (see below).

Options (opts)

:disposition

The disposition of the file send. Defaults to “attachment”.

:filename

The name to use for the file. Defaults to the filename of file.

:type

The content type.

:api: public

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

Path to file to send to the client.

opts

Options for sending the file (see below).

Options (opts)

:disposition

The disposition of the file send. Defaults to “attachment”.

:filename

The name to use for the file. Defaults to the filename of file.

:type

The content type.

Returns

IO

An I/O stream for the file.

:api: public

     # File lib/merb-core/controller/mixins/controller.rb, line 183
183:     def send_file(file, opts={})
184:       opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))
185:       disposition = opts[:disposition].dup || 'attachment'
186:       disposition << %(; filename="#{opts[:filename] ? opts[:filename] : File.basename(file)}")
187:       headers.update(
188:         'Content-Type'              => opts[:type].strip,  # fixes a problem with extra '\r' with some browsers
189:         'Content-Disposition'       => disposition,
190:         'Content-Transfer-Encoding' => 'binary'
191:       )
192:       Proc.new do |response|
193:         file = File.open(file, 'rb')
194:         while chunk = file.read(16384)
195:           response.write chunk
196:         end
197:         file.close
198:       end
199:     end
stream_file(opts={}, &stream) click to toggle source

Streams a file over HTTP.

Parameters

opts

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

The disposition of the file send. Defaults to “attachment”.

:type

The content type.

:content_length

The length of the content to send.

:filename

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
252:     def stream_file(opts={}, &stream)
253:       opts.update(Merb::Const::DEFAULT_SEND_FILE_OPTIONS.merge(opts))
254:       disposition = opts[:disposition].dup || 'attachment'
255:       disposition << %(; filename="#{opts[:filename]}")
256:       headers.update(
257:         'Content-Type'              => opts[:type].strip,  # fixes a problem with extra '\r' with some browsers
258:         'Content-Disposition'       => disposition,
259:         'Content-Transfer-Encoding' => 'binary',
260:         # Rack specification requires header values to respond to :each
261:         'CONTENT-LENGTH'            => opts[:content_length].to_s
262:       )
263:       Proc.new do |response|
264:         stream.call(response)
265:       end
266:     end

Private Instance Methods

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

Process a redirect url with options, appending messages onto the url as query params

Parameter

url

the url being redirected to

Options (opts)

:message

A hash of key/value strings to be passed along within the redirect query params.

:notice

A shortcut to passing :message => {:notice => “…”}

:error

A shortcut to passing :message => {:error => “…”}

:success

A shortcut to passing :message => {:success => “…”}

Returns

String

the new url with messages attached

    

:api: private

     # File lib/merb-core/controller/mixins/controller.rb, line 380
380:     def handle_redirect_messages(url, opts={})
381:       opts = opts.dup
382: 
383:       # check opts for message shortcut keys (and assign them to message)
384:       [:notice, :error, :success].each do |message_key|
385:         if opts[message_key]
386:           opts[:message] ||= {}
387:           opts[:message][message_key] = opts[message_key]
388:         end
389:       end
390:       
391:       # append message query param if message is passed
392:       if opts[:message]
393:         notice = Merb::Parse.escape([Marshal.dump(opts[:message])].pack("m"))
394:         u = ::URI.parse(url)
395:         u.query = u.query ? "#{u.query}&_message=#{notice}" : "_message=#{notice}"
396:         url = u.to_s
397:       end
398:       
399:       url
400:     end
only_runs_on_mongrel!() click to toggle source

Marks an output method that only runs on the Mongrel webserver.

Raises

NotImplemented

The Rack adapter is not mongrel.

:api: private

     # File lib/merb-core/controller/mixins/controller.rb, line 355
355:     def only_runs_on_mongrel!
356:       unless Merb::Config[:log_stream] == 'mongrel'
357:         raise(Merb::ControllerExceptions::NotImplemented, "Current Rack adapter is not mongrel. cannot support this feature")
358:       end
359:     end

Disabled; run with --debug to generate this.

[Validate]

Generated with the Darkfish Rdoc Generator 1.1.6.