7

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
dee
  • 1,848
  • 1
  • 22
  • 34
  • 1
    !object.blank? == object.present?, and it's also interesting to check this SO question: http://stackoverflow.com/questions/885414/a-concise-explanation-of-nil-v-empty-v-blank-in-ruby-on-rails – siekfried Jun 12 '13 at 13:41

2 Answers2

9

.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
zeantsoi
  • 25,857
  • 7
  • 69
  • 61
  • I understand, thanks. I still can't figure out if it makes a difference in my use case, though... – dee Jun 12 '13 at 13:40
  • It doesn't make a difference. Don't worry about it. – Alex D Jun 12 '13 at 14:16
  • "`blank?` evaluates to `true` when evaluating a string that is not empty and ..." - is this accurate? In my rails console, evaluating `''.blank?` returns `true`. So does `nil.blank?`. – Jon Schneider Nov 16 '17 at 19:05
3

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.

Josnidhin
  • 12,469
  • 9
  • 42
  • 61
  • 1
    `"".nil? # => false` | `"".present? # => false` | `"".blank # => true` | – Gareth Jun 12 '13 at 13:39
  • 1
    See also the documentation for [`Object#blank?`](http://apidock.com/rails/Object/blank%3F) - An object is blank if it’s false, empty, or a whitespace string. For example, “”, “ ”, nil, [], and {} are all blank – Gareth Jun 12 '13 at 13:41
  • I understand now, but I'm not sure if there's a subtle issue with my use case... i.e. if I changed from `!nil?` to `present?` -- as far as I can see it's a negative. – dee Jun 12 '13 at 13:43