1

在我的 Rails 应用程序中,我有这段代码:

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

有人可以解释 if 语句以及这里发生了什么吗?我对 ROR 不太熟悉,所以我很难弄清楚这种语法。

4

2 回答 2

3

这是一个描述

  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

这意味着,用人类语言

如果请求发送一个空params[:auth_token](或无)并且HTTP 请求在其标头中包含 key 的值(可能为空)"auth_token",它将设置params[:auth_token]true;

更长的版本:

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

较短的版本(您可以将代码重构为此):

def get_auth_token
    params[:auth_token] = true if params[:auth_token].blank? && request.headers["auth_token"].present?
end
于 2013-05-31T01:36:54.120 回答
3

第一个答案是错误的。你的代码可以大致翻译成这样:

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

也就是说,如果 params 中的“auth_token”为空,则从标头中将其设置为“auth_token”。它不仅设置为,true因为布尔运算符在 Ruby 中不返回单例布尔值:

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

我只从您的代码中省略了一个条件,这里是完整的翻译:

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

唯一的区别是何时params[:auth_token] = ""request.headers["auth_token"] = nil参数不会更改为 nil。这是一件非常小的事情,我不确定你是否关心这个。

如果不涉及任何空白字符串,您可以使用 Ruby 的“或等于”运算符更清楚地表达它:

params[:auth_token] ||= request.headers["auth_token"]
于 2013-05-31T03:08:43.933 回答