I have created some modules using scaffold, but I can’t understand how can we use respond_to without relating to an object or anything?
respond_to do |format|
format.html { redirect_to posts_url }
format.json { head :ok }
end
I have researched about the ‘do’ and found that it is like ‘each’ deals with enumerable object
the part between
doandendis a ruby block. If you’re familiar with anonymous functions, it shares some similitudes with this concept.respond_tois an instance method on your controller ; the block is passed to this method.|format|is the argument that this method passes to the block at some point of its execution.the good thing with blocks is that they are evaluated in the context (“binding”) of the method caller, in this case the instance of your controller. So you can use any variables or methods you could use in your controller inside your block – even if you were calling a method on another object. This is a very powerful feature from Ruby, and as @Niklaos and @Perry said, you should definitely learn more about ruby idioms because these blocks are everywhere !
the other syntax for a block is
One more thing : many iterator methods use blocks in ruby, but blocks are not limited to iteration. ‘each’ for example is an iterator that yields (passes to the block) every member of a collection from which it is called on, one after another.
So, to answer your question the
respond_tomethod yields anActionController::MimeResponds::Collectorobject to the block ; in this block you configure different responses for different MIME types. To do so you pass another block to one or many of the MIME methods (html,json,etc.) of this object.The controller then uses this Collector object to determine the appropriate response to a request (render an html.erb template, or format content as json, etc. – note that redirect_to, for example, is indeed a controller instance method). A good documentation for respond_to can be found here.
Hope this helped !