Is it safe to assume that !object.nil? == object.present?
in Rails, or are there gotchas? Here's a 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
In Ruby, nil is—you've guessed it—an object. It's the single instance of the NilClass class. Since nil in Ruby is just an object like virtually anything else, this means that handling it is not a special case.
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
Well, nil is a special Ruby object used to represent an “empty” or “default” value. It's also a “falsy” value, meaning that it behaves like false when used in a conditional statement.
In Ruby, nil is a special value that denotes the absence of any value. Nil is an object of NilClass. nil is Ruby's way of referring to nothing or void.
.present?
is the negation of .blank?
, which is similar but decidedly unique from .nil?
.
.nil?
only evaluates whether an object is NilClass
.
.blank?
evaluates to true
when evaluating a string that is not empty and may (or may not) contain whitespace.
It's superfluous to your question, but it's probably handy to note that .blank?
and .present?
are Rails methods, whereas .nil?
is pure Ruby.
EDIT:
If, in your example, object
is equal to false
, then no, it's not safe to assume that !object.nil? == object.present?
. However, if object
is actually a Ruby/Rails object, then it's safe to assume that the statement will evaluate to true.
!false.nil? == false.present? #=> false
In rails generally I dont think so according to the docs here.
But the following should be true
!object.blank? == object.present?
In your case I think it should be true because of how the method current_user
is defined.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With