1

Here is a Rails code:

respond_to do |format|
  format.html
  format.xml { render :xml => @users }
  format.json { render :json => @users }
end

I know what it does. But I don't know the meaning of the commands syntax-wise.

  1. format.xml -- what is xml, is this a method which an object format has, correct? Where do I find its signature (or description)?
  2. { } -- a block or a hash? I think this is a block.
  3. render -- a method? where do I find its signature (where in api docs)?
  4. :xml => @users -- a hash, where :xml => is a key, correct?

So it could be reprented as, right?:

respond_to do |format|
  format.html
  format.xml do
    render(:xml => @users)
  end 
  format.json do
    render(:json => @users)
  end
end
Andrew Marshall
  • 95,083
  • 20
  • 220
  • 214

2 Answers2

0
  1. format comes from the request made to the method, http://app.com/controller/method.format where format could be .html or .csv etc. The meaning of format.xml is simply to check if the user requested an xml page (http://app.com/controller/method.xml.
  2. Block, just like you describe.
  3. At the apidock! http://apidock.com/rails/ActionController/Base/render
  4. Correct, render will act depending on the key that exists. In your case, as the existing key is :xml the render method will output @users formatted as XML.
Matt
  • 13,948
  • 6
  • 44
  • 68
0

format.*

Using the debugger, I learnt that format is an instance of ActionController::MimeResponds::Collector. It includes AbstractController::Collector, which uses method_missing to respond to various format calls.

if Mime::SET.include?(mime_constant)
  AbstractController::Collector.generate_method_for_mime(mime_constant)
  send(symbol, &block)
else
  # ...

{ render xml: ... }

Looking at method_missing, it's clear that it expects a block.

render

Yes, render is a method. Documentation.

:xml => @user

Yes, it's a hash. The key is the symbol :xml. It can also be written as

render xml: @user

render(xml: @user)

render({xml: @user})
render({:xml => @user})
James Lim
  • 12,915
  • 4
  • 40
  • 65