Sasgorilla
Sasgorilla

Reputation: 3130

What determines the return value of `present?`?

Some valid ActiveRecord objects return false for present?:

object.nil? # => false
object.valid? # => true
object.present? # => false
object.blank? # => true

I prefer object.present? over not object.nil?. What determines the return value of present?/blank??

EDIT: Found the answer: I had redefined the empty? method on this class, not the blank? or present? method; along the lines of @Simone's answer, blank? is using empty? behind the scenes.

Upvotes: 2

Views: 744

Answers (2)

eugen
eugen

Reputation: 9226

From the documentation for Object#present?

An object is present if it's not blank.

In your case, object is blank, so present? will return false. Validity of the object does not really matter.

Upvotes: 1

Simone Carletti
Simone Carletti

Reputation: 176412

present? is the opposite of blank?. blank? implementation depends on the type of object. Generally speaking, it returns true when the value is empty or like-empty.

You can get an idea looking at the tests for the method:

  BLANK = [ EmptyTrue.new, nil, false, '', '   ', "  \n\t  \r ", ' ', "\u00a0", [], {} ]
  NOT   = [ EmptyFalse.new, Object.new, true, 0, 1, 'a', [nil], { nil => 0 } ]

  def test_blank
    BLANK.each { |v| assert_equal true, v.blank?,  "#{v.inspect} should be blank" }
    NOT.each   { |v| assert_equal false, v.blank?, "#{v.inspect} should not be blank" }
  end

  def test_present
    BLANK.each { |v| assert_equal false, v.present?, "#{v.inspect} should not be present" }
    NOT.each   { |v| assert_equal true, v.present?,  "#{v.inspect} should be present" }
  end

An object can define its own interpretation of blank?. For example

class Foo
  def initialize(value)
    @value = value
  end
  def blank?
    @value != "foo"
  end
end

Foo.new("bar").blank?
# => true

Foo.new("foo").blank?
# => false

If not specified, it will fallback to the closest implementation (e.g. Object).

Upvotes: 7

Related Questions