Would someone be able to break down the Ruby specifics of what each of these statements consist of in as far as methods, parameters, block interpretations etc. This is very common to see in Rails code and I’m trying to understand how the Ruby interpreter reads this code:
respond_to do |format|
format.xml { render :layout => false }
end
In as far as I understand, respond_to is a method that’s taking one parameter to it, a block. So I’m guessing it’s written something like:
def respond_to(&block)
block.call
end
.. or something similar?
in the block itself, format is the object respond_to passes into the block and xml is what the request is set to, at which point it calls a block in itself if the request is asking for XML type data and goes ahead and invokes a render method, passing it a keyword based argument, :layout => false?
Would someone clean up my understanding of how they above works. This type of code is all over Rails and I’d like to understand it before using it more.
This is a typical Implementation Pattern for Internal DSLs in Ruby: you yield an object to the block which then itself accepts new method calls and blocks and thus guides the interface. (Actually, it’s pretty common in Java, too, where it is used to get meaningful code completion for Internal DSLs.)
Here’s an example:
Now you have a mapping of formats to executable pieces of code stored in
@respondersand you can call it later and in a different place, whenever, whereever and however often you want:As I hinted at above, if instead of a dumb proxy object that simply uses
method_missing, you were to use one which had the most important methods (xml,html,json,rss,atomand so on) predefined, a sufficiently intelligent IDE could even give you meaningful code completion.Note: I have absolutely no idea whether this is how it is implemented in Rails, but however it is implemented, it is probably some variation of this.