Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Ruby-仅当结果不为false时才分配变量_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails Ruby-仅当结果不为false时才分配变量

Ruby on rails Ruby-仅当结果不为false时才分配变量,ruby-on-rails,ruby,Ruby On Rails,Ruby,具体来说,我的问题是在阅读has_secure_密码的源代码以及最终的身份验证方法时出现的 def authenticate(unencrypted_password) BCrypt::Password.new(password_digest) == unencrypted_password && self end 我希望有一个实例变量来保存用户,但仅当身份验证方法的结果返回用户而不是false时 unless @user = user.authenticate(...

具体来说,我的问题是在阅读has_secure_密码的源代码以及最终的身份验证方法时出现的

def authenticate(unencrypted_password)
    BCrypt::Password.new(password_digest) == unencrypted_password && self
end
我希望有一个实例变量来保存用户,但仅当身份验证方法的结果返回用户而不是false时

unless @user = user.authenticate(...)
  ...
end

现在我想在稍后调用的方法中访问@user变量。我尝试使用安全导航操作符,但它只在@user为nil且不为false时起作用。基本上,我不想在对用户调用方法时检查@user是否为false。对未经身份验证的用户进行操作时,不应调用该方法。有没有一种简单的方法来编写这样的语句,或者我是否每次都需要检查@user是否为false?

(@user=user.authenticate(…)| nil)
?如果身份验证成功,它将返回用户对象,否则它将返回false,其中带有短路以给出RHS(
nil
)@kiddorails是否最好用单独的方法包装此语句,还是应该像它一样留在控制器中?此调用之前,
user
(loca变量)是什么?似乎
@user=user if user.authenticate(#…)
就足够了。不是吗?@engineersmnky是的,它是一个局部变量。我寻找一种可以链接的方式来表达它,而不用编写太多的代码。这就是为什么我问为它定义一个方法是否有意义。这样我就可以编写
@user=user.authenticate\u或\u nil(…)
,并且我可以使用safe navigator调用所有其他方法
@user&.methodA(…)
。更多一点的上下文可能会有用,因为我不知道为什么您甚至需要调用未经验证的“用户”上的任何内容。无论哪种方式,我的建议都会如期发挥作用