Generating a scaffold like this:
rails generate scaffold User name:string email:string
creates bits of code that look like this in the controller class:
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
At first I didn’t know what this meant, so I went looking and found this,
which I think adequately explains most of it. But format is supposed to end up being a Responder class. Well, there doesn’t seem to be any xml or html or json members declared in the Responder class. Where do they come from?
PS:
It seems cruel that the scaffold developer would name the block parameter “format” when it ends up being a Responder (and the format information comes from the .html, .xml, .json, or whatever) to make the code sound a bit like English but hinder understanding of what’s actually going on. In fact, Responder::respond is defined like so, which seems too coincidental:
def respond
method = "to_#{format}"
respond_to?(method) ? send(method) : to_format
end
But I don’t see how the format here (in “to_#{format}”) can be related to the block parameter named format. And to be clear, it’s NOT an instance variable because it’s lacking an @ sign, right?
As the blog explains later, basically from here the Responder instance handles .html and .xml via method_missing, depending on mime types your rails app can process.
One of the nice blogs that describe method_missing is here.
Basically, the responder’s method_missing will get called when js and json methods are invoked. The method_missing of responder class will get the “missing method_name” (that is, :js or :json symbols) as its first parameter, which will drive its rendering logic.