Christopher Dicely
3/8/2008 2:54:00 AM
On Fri, Mar 7, 2008 at 6:32 PM, Daniel Mendler <dmendler@wurzelteiler.de> wrote:
> Hi!
>
> Why is this code invalid?
>
>
> respond_to do |format|
> format.html
> format.xml { render :xml => @books }
> format.js { render :update { |p| p.replace_html 'books_table',
> :partial => 'books' } } # <---
> end
>
> ...and this code valid?
>
> respond_to do |format|
> format.html # search.html.erb
> format.xml { render :xml => @books }
> format.js { render :update do |p|; p.replace_html 'books_table',
> :partial => 'books'; end }
> end
>
> I do not understand when to use do-end blocks and when to use bracket
> constructs.
They are not equivalent: they mean the same thing, but blocks
delineated by braces bind more tightly than do ... end blocks. This is
an issue when you have parameters to a method call that are not
enclosed with parentheses. In your snippet this:
--
render :update { |p| ... }
--
Is not equivalent to:
--
render :update do |p| ... end
--
But instead to:
--
render (:update do |p| ... end)
--
Since :update is a Symbol and can't take a block, this is invalid.
You could still use braces, but you would have to parenthesize the
argument to render, as so:
--
render(:update) {|p| ... }
> According to the documentation they are equivalent...
Which documentation? Your code seems to be Rails code, and its true
that the very minimal introduction to Ruby in Appendix A of _Agile Web
Development with Rails_ doesn't seem to cover this difference in the
section on blocks. If you are trying to learn Ruby and Rails
simultaneously, I would suggest you to refer to a good general Ruby
book along with AWDR; AWDR introduces Rails quite well, but its
coverage of Ruby is vestigial. _Programming Ruby_, _The Ruby Way_,
_Ruby for Rails_, and _The Ruby Programming Language_ are all good
choices, each with its own particular strengths and weaknesses.