这种导轨条件有什么作用?

时间:2013-05-31 01:31:20

标签: ruby-on-rails

在我的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不太流利,所以我很难搞清楚这种语法。

2 个答案:

答案 0 :(得分: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](或无) AND   HTTP请求在其标头中包含密钥"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

答案 1 :(得分:3)

第一个答案是不正确的。您的代码可以大致翻译成:

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

也就是说,如果" auth_token"在params中它是空白的,它被设置为" 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参数不会变为零时。这是一个非常小的事情,我不确定你是否关心这一点。

如果没有涉及任何空白字符串,您可以使用Ruby"或等于"更清楚地表达它。操作者:

params[:auth_token] ||= request.headers["auth_token"]
相关问题