Module: Rack::RespondTo::ClassMethods

Defined in:
lib/rack/respond_to.rb

Instance Method Summary collapse

Instance Method Details

#respond_to {|format| ... } ⇒ Object

Allows defining different actions and returns the one which corresponds to the highest ranking value in the RespondTo.media_types list.

If no handler is defined for the highest ranking value, respond_to will cascade down the RespondTo.media_types list until it finds a match. Returns nil if there is no match.

Wildcard media types (/, text/, etc.) will trigger the first matching format definition, so order matters if you expect the Accept header to contain any (a nil Accept header, for instance, will be turned into '/*' as per rfc2616-sec14.1). Simply define the 'default' handler first (usually html), and it will work like a charm.

Examples
RespondTo.media_types = ['text/html', 'application/xml']

respond_to do |format|
format.html { 'html' }
format.xml  { 'xml'  }
end
#=> 'html'

RespondTo.media_types = ['text/html', 'application/xml']

respond_to do |format|
format.xml  { 'xml' }
format.txt  { 'txt'  }
end
#=> 'xml'

RespondTo.media_types = ['text/html', 'application/json']

respond_to do |format|
format.xml  { 'xml' }
format.txt  { 'txt'  }
end
#=> nil

RespondTo.media_types = ['*/*']

respond_to do |format|
format.html { 'html' }
format.xml  { 'xml'  }
end
#=> 'html'

RespondTo.media_types = ['*/*']

respond_to do |format|
format.xml  { 'xml'  }
format.html { 'html' }
end
#=> 'xml'

RespondTo.media_types = ['text/*']

respond_to do |format|
format.xml  { 'xml'  } # application/xml  (skip)
format.html { 'html' } # text/html        (match)
format.txt  { 'txt'  }
end
#=> 'html'

Yields:

  • (format)


157
158
159
160
161
162
163
# File 'lib/rack/respond_to.rb', line 157

def respond_to
  format = Format.new
  yield format
  type, handler = Helpers.match(RespondTo.media_types, format)
  RespondTo.selected_media_type = type
  handler.nil? ? nil : handler.call
end