开发者

In Ruby on Rails, what kind of design pattern is to use false to denote don't do DB look up and nil to denote ok to look up?

In Restful Authentication, I found th开发者_如何学运维at current_user is quite intricate that, when @current_user is set to false, then it means don't try to find user again (usually from DB), while nil means that's ok, can look up again in DB:

Line 8 of lib/authenticated_system.rb

def current_user
  @current_user ||= (login_from_session 
                      || login_from_basic_auth 
                      || login_from_cookie) unless @current_user == false
end

the intricate thing is, if it tries to look up the DB from login_from_session, etc, and can't find it, then the final value that gets assigned to @current_user is nil, and the method returns nil (which is the last evaluated value in the method). Unless there are two other places in the code elsewhere that actually can set @current_user to false, and that will trigger the unless, causing the whole statement to return nil, while @current_user remains as false, and the method returns nil...

I was almost speechless for the code to rely on these intricate facts. false has special meaning, and nil has special meaning in the code, but is not documented, not commented, and current_user can be nil, while @current_user can continue to be false. Is it actually a design pattern, so people are familiar with it and know it well?


RestfulAuthentication is considered quite old and nasty at this point in Rails history, partly because of code like what you are pointing out.

I think most people would advise you to go with a more modern authentication solution such as Devise or Authlogic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜