sbonkosky
sbonkosky

Reputation: 2557

What does this rails condition do?

In my rails app I have this piece of code:

  def get_auth_token
    if auth_token = params[:auth_token].blank? && request.headers["auth_token"]
      params[:auth_token] = auth_token
    end
  end

Can someone explain the if statement and what happens here? I'm not too fluent in ROR so I'm having a hard time figuring this syntax out.

Upvotes: 1

Views: 77

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

Here is a description:

  def get_auth_token
    if auth_token = params[:auth_token].blank? && request.headers["auth_token"]
    # sets the var auth_token to true/false inside the IF statement to
    # true IF params[:auth_token] is empty or nil AND 
    # request.headers["auth_token"] is not nil (but could be empty)
      params[:auth_token] = auth_token
      # set the params[:auth_token] to auth_token (which could only be true)
    end
  end

That means, in human language:

If the request sent an empty params[:auth_token] (or none) AND the HTTP request contains in its headers a value (could be empty) for the key "auth_token", it will set the params[:auth_token] to true;

The longer version:

def get_auth_token
  auth_token = ( params[:auth_token].blank? && request.headers["auth_token"] ) # can be true/false
  if auth_token
    params[:auth_token] = auth_token
  end
end

The shorter version (you could refactor your code to this):

def get_auth_token
    params[:auth_token] = true if params[:auth_token].blank? && request.headers["auth_token"].present?
end

Upvotes: 3

Simon Perepelitsa
Simon Perepelitsa

Reputation: 20639

The first answer is incorrect. Your code can be roughly translated into this:

if params[:auth_token].blank?
  params[:auth_token] = request.headers["auth_token"]
end

That is, if "auth_token" in params is blank it is set to "auth_token" from headers. It isn't set only to true because boolean operators do not return singleton booleans in Ruby:

true && "abcde" #=> "abcde"
nil || 42 #=> 42
nil && nil #=> nil

I only omitted one conditional from your code, here goes the complete translation:

if params[:auth_token].blank? and request.headers["auth_token"]
  params[:auth_token] = request.headers["auth_token"]
end

The only difference is when params[:auth_token] = "" and request.headers["auth_token"] = nil the parameter won't change to nil. Which is a very minor thing I'm not sure if you care about this.

If there weren't any blank strings involved, you could express it more clear with Ruby's "or equal" operator:

params[:auth_token] ||= request.headers["auth_token"]

Upvotes: 3

Related Questions