Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is !object.nil? == object.present? in Rails?

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
like image 486
dee Avatar asked Jun 12 '13 13:06

dee


People also ask

Is nil an object in Ruby?

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.

How do I check if an object is nil in Ruby?

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).

Is nil blank in Ruby?

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.

What is nil in Ruby on Rails?

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.


2 Answers

.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
like image 56
zeantsoi Avatar answered Oct 06 '22 08:10

zeantsoi


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.

like image 33
Josnidhin Avatar answered Oct 06 '22 08:10

Josnidhin