blueblank
blueblank

Reputation: 4904

Full range of options for respond_to format.*

I'm looking into rendering more complex responses.

Specifically, I am searching for options for formatting yaml and json responses with multiple levels, but right now I cannot locate any api information on options.

I've seen something about :include and :only in other sample controllers. I'm wondering what the full range of options are for more complex rendering of documents (specifically yaml, but I'd like to learn for all)

For example:

 def index
    @people = Person.find(:all)

    respond_to do |format|
      format.*  ?????????????????????
    end
  end

background: trying to assemble what is for me more complex yaml ouput and seeing what and how I can from the controller as opposed to having to build a specific view.

Upvotes: 0

Views: 1111

Answers (2)

edgerunner
edgerunner

Reputation: 14983

After reading through the rails code, I can safely say that there isn't anything else that you don't know about. (Although the documentation for respond_to in block form seems to be missing from the API docs)

Basically there are two ways to use respond_to

Declarative

class WidgetsController
  respond_to :html, :xml, :json, only: [:index, :show]

  def index
    @widgets = Widget.all
    respond_with @widgets
  end
  …
end

Block

class WidgetsController
  def index
    @widgets = Widget.all
    respond_to do |format|
      format.html #do default
      format.pdf {…} # handle in block
      format.any(:json, :xml) {…} # handle anything listed
    end
  end
  …
end

You can't use the options on the block form (it is a different method definition entirely), and :only and :except are the only options that the declarative version accepts.

Upvotes: 3

Cicero Oliveira
Cicero Oliveira

Reputation: 69

A standard set of MIME types is supported: :html, :xhtml, :text, :txt, :js, :css, :ics, :csv, :xml, :rss, :atom, :yaml, :url_encoded_form, :multipart_form, :json.

To create new ones, register them in the mime_types.rb initializer

# Add new mime types for use in respond_to blocks:
# Mime::Type.register "text/richtext", :rtf
# Mime::Type.register_alias "text/html", :iphone

I hope this helps.

Upvotes: 4

Related Questions