Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails/ruby "and return false" syntax

I've seen this code in a rails tutorial I'm doing

def access_denied
  redirect_to login_path, :notice => "Please log in to continue" and return false
end

Before learning rails, I did a large amount of ruby research and none of the books I read covered this "and return false" syntax going on here. I can't find any mention of it in the rails syntax, is anyone able to provide a link or any explanation that would clear this up?

I don't understand the need for the "and" in here as I thought ruby would always return the last evaluated expression.

like image 701
Mikey Hogarth Avatar asked Jan 11 '12 19:01

Mikey Hogarth


3 Answers

The and is there only for you to be able to write the return false at the same line as the previous statement.

It's equivalent of doing this:

redirect_to login_path, :notice => "Please log in to continue"
return false

it's not exactly the same because with the "and" it would only return false if the redirect_to method returns something that isn't nil or false but as it almost always returns something that is not nil nor false then the right side of the statement is always executed (and false is returned).

The and in Ruby is just an alias to && and behaves exactly like it with only one difference, it has a lower precedence than all other pieces of the statement, so first it evaluates whatever is on it's left and then gets applied. Ruby also has the or which is the same as || but with a lower precedence in expressions.

like image 121
Maurício Linhares Avatar answered Oct 02 '22 01:10

Maurício Linhares


redirect_to login_path, :notice => "Please log in to continue" is a normal expression in Ruby that does not return false (or nil, see the source code), so program execution continues (to check the second part after AND) and return false can be executed.

like image 29
Marek Příhoda Avatar answered Oct 02 '22 01:10

Marek Příhoda


This kind of construct used to be used with a filter, when filter return values were expected. The false would halt normal request processing.

So if a controller looked like this:

class FooController < ActionController::Base
  before_filter :access_denied
  # etc.
end

None of the controller's actions would run; this method was likely designed to be called from a filter, like:

def check_access
  return access_denied unless current_user.has_access
end

These days filter return values are ignored.

It could be used as a normal method in an action to stop processing the action and return after the redirect, so no other logic/rendering/etc. is run inside the controller.

like image 37
Dave Newton Avatar answered Oct 02 '22 01:10

Dave Newton