新手问题 两个叹号

xiaoronglv · 2012年08月27日 · 最后由 xiaoronglv 回复于 2012年08月28日 · 4876 次阅读

http://guides.rubyonrails.org/action_controller_overview.html#filters

!!current_user 是什么意思?current_user 是方法吗?

class ApplicationController < ActionController::Base
  before_filter :require_login

  private

  def require_login
    unless logged_in?
      flash[:error] = "You must be logged in to access this section"
      redirect_to new_login_url # halts request cycle
    end
  end

  # The logged_in? method simply returns true if the user is logged
  # in and false otherwise. It does this by "booleanizing" the
  # current_user method we created previously using a double ! operator.
  # Note that this is not common in Ruby and is discouraged unless you
  # really mean to convert something into true or false.
  def logged_in?
    !!current_user
  end
end

注释都写着啊。

#1 楼 @yesmeck 注释的意思是是否为“current_user 是已经定义好的方法,两个叹号执行”?

从未见过两个叹号的写法,所以感觉有些奇怪。

两次取反,确保返回值是一个布尔值

相当于判断是否存在,而且两个!非常醒目

#3 楼 @Rei 经你这么一说,明白了。灰常感谢 😄

需要 登录 后方可回复, 如果你还没有账号请 注册新账号