1 class Object
2 # An object is blank if it's false, empty, or a whitespace string.
3 # For example, "", " ", +nil+, [], and {} are blank.
4 #
5 # This simplifies:
6 #
7 # if !address.nil? && !address.empty?
8 #
9 # ...to:
10 #
11 # if !address.blank?
12 def blank?
13 respond_to?(:empty?) ? empty? : !self
14 end
15
16 # An object is present if it's not blank.
17 def present?
18 !blank?
19 end
20
21 # Returns object if it's #present? otherwise returns nil.
22 # object.presence is equivalent to object.present? ? object : nil.
23 #
24 # This is handy for any representation of objects where blank is the same
25 # as not present at all. For example, this simplifies a common check for
26 # HTTP POST/query parameters:
27 #
28 # state = params[:state] if params[:state].present?
29 # country = params[:country] if params[:country].present?
30 # region = state || country || 'US'
31 #
32 # ...becomes:
33 #
34 # region = params[:state].presence || params[:country].presence || 'US'
35 def presence
36 self if present?
37 end
38 end
39
40 class NilClass #:nodoc:
41 def blank?
42 true
43 end
44 end
45
46 class FalseClass #:nodoc:
47 def blank?
48 true
49 end
50 end
51
52 class TrueClass #:nodoc:
53 def blank?
54 false
55 end
56 end
57
58 class Array #:nodoc:
59 alias_method :blank?, :empty?
60 end
61
62 class Hash #:nodoc:
63 alias_method :blank?, :empty?
64 end
65
66 class String #:nodoc:
67 def blank?
68 self !~ /\S/
69 end
70 end
71
72 class Numeric #:nodoc:
73 def blank?
74 false
75 end
76 end