Forum: Ruby on Rails code snippet

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Spyros V. (Guest)
on 2006-05-31 20:49
Hello people,
found the following controller code and I wonder what it does and
particulary the "and return" part.


if @order == nil then
   redirect_to_checkout("blabla") and return
end

thanks
Brian H. (Guest)
on 2006-05-31 21:27
(Received via mailing list)
On May 31, 2006, at 12:49 PM, Spyros Vasileiadis wrote:
> Hello people,
> found the following controller code and I wonder what it does and
> particulary the "and return" part.
>
> if @order == nil then
>    redirect_to_checkout("blabla") and return
> end

Well, I would have probably written this code as:

   redirect_to_checkout("blabla") and return if @order.nil?

Since there's only one line in the if block, that basically means
there's no need for the block.

As for the "and return" part of the code, that is telling the
controller to stop all processing after calling what looks like a
custom version of the redirect_to helper method. The "and" is used
because that guarantees that both sides of the boolean expression
will be called, which means the return part will always fire, if
@order is nil. You couldn't do this with an "or" since the
redirect_to_checkout could return a true value, which would stop the
processing of the boolean expression.

FYI, I've also written this kind of expression like this:

   return(redirect_to_checkout("blabla")) if @order.nil?

But I've since switched to using the "and return" format, mostly
because it reads a lot cleaner.

-Brian
This topic is locked and can not be replied to.