简体   繁体   中英

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.

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 (eg Object ).

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM