present.txt

Roger Pack, 07/14/2012 03:39 PM

Download (868 Bytes)

 
1
Feature #6731 [add new method "Object.present?" as a counter to #empty?]
2

    
3
Basically Object#present? , "An object is present if it?s not #empty?" [2]
4
or, in other words, "is there any data inside?"
5

    
6
Examples:
7

    
8
>> [].present?
9
=> false
10
>> [3].present?
11
=> true
12
>> ''.present?
13
=> false # because it's #empty?
14
>> 'a'.present?
15
=> true
16
>> nil.present?
17
=> false
18

    
19
Example usage:
20

    
21
  button.text=text if text.present? # I only care whether the text actually was set to something, and also don't want to worry about whether it's nil or not.
22

    
23
Thanks.
24

    
25
Basic implementation ([1]):
26

    
27
class Object
28

    
29
  def present?
30
    !(respond_to?(:empty?) ? empty? : !self)
31
  end
32

    
33
end
34

    
35
[1] http://stackoverflow.com/a/4649452/32453
36
[2] http://api.rubyonrails.org/classes/Object.html#method-i-present-3F they also use #blank but that's for a different feature request.