It? Object.nil? == object.present? in Rails?

Is it possible to assume that !object.nil? == object.present? !object.nil? == object.present? in Rails, or are there gotchas? Here is the scenario:

  def signed_in? !current_user.nil? # Would current_user.present? mean the same thing here? end def sign_in(user) cookies[:token] = user.token self.current_user = user end def current_user @current_user ||= User.find_by(token: cookies[:token]) if cookies[:token] end 
+4
source share
2 answers

.present? is a .blank? denial .blank? Which is similar, but clearly unique from .nil? .

.nil? evaluates only the NilClass object.

.blank? evaluates to true when evaluating a string that is not empty and may contain (or not contain) spaces.

This is superfluous to your question, but it is probably convenient to note that .blank? and .present? are Rails methods whereas .nil? - pure Ruby.

EDIT:

If in your example object is false , then no, it is unsafe to assume that !object.nil? == object.present? !object.nil? == object.present? . However, if the object is actually a Ruby / Rails object, then we can safely assume that the operator will evaluate to true.

 !false.nil? == false.present? #=> false 
+5
source

On rails, I usually don’t think about it according to the docs here .

But the following should be true:

 !object.blank? == object.present? 

In your case, I think this should be true because of how the current_user method is defined.

+2
source

Source: https://habr.com/ru/post/1485813/


All Articles