Module: Corefines::Object::Blank

Defined in:
lib/corefines/object.rb

Constant Summary collapse

BLANK_RE =
/\A[[:space:]]*\z/

Instance Method Summary collapse

Instance Method Details

#blank?Boolean

An object is blank if it's false, empty, or a whitespace string. For example, '', ' ', "\t\n\r", "\u00a0", nil, [], {} are all blank.

This simplifies

address.nil? || address.empty?

to

address.blank?

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/corefines/object.rb', line 40

module Blank

  BLANK_RE = /\A[[:space:]]*\z/

  refine ::Object do
    def blank?
      respond_to?(:empty?) ? !!empty? : !self
    end

    def presence
      self unless blank?
    end
  end

  refine ::NilClass do
    def blank?
      true
    end
  end

  refine ::FalseClass do
    def blank?
      true
    end
  end

  refine ::TrueClass do
    def blank?
      false
    end
  end

  refine ::Array do
    alias_method :blank?, :empty?
  end

  refine ::Hash do
    alias_method :blank?, :empty?
  end

  refine ::Numeric do
    def blank?
      false
    end
  end

  refine ::String do
    def blank?
      BLANK_RE === self
    end
  end
end

#presenceObject?

Returns object if it's not #blank?, otherwise returns nil. obj.presence is equivalent to obj.blank? ? nil : obj.

This is handy for any representation of objects where blank is the same as not present at all. For example, this simplifies a common check for HTTP POST/query parameters:

state = params[:state] if params[:state].present?
country = params[:country] if params[:country].present?
region = state || country || 'CZ'

becomes…

region = params[:state].presence || params[:country].presence || 'CZ'

40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
# File 'lib/corefines/object.rb', line 40

module Blank

  BLANK_RE = /\A[[:space:]]*\z/

  refine ::Object do
    def blank?
      respond_to?(:empty?) ? !!empty? : !self
    end

    def presence
      self unless blank?
    end
  end

  refine ::NilClass do
    def blank?
      true
    end
  end

  refine ::FalseClass do
    def blank?
      true
    end
  end

  refine ::TrueClass do
    def blank?
      false
    end
  end

  refine ::Array do
    alias_method :blank?, :empty?
  end

  refine ::Hash do
    alias_method :blank?, :empty?
  end

  refine ::Numeric do
    def blank?
      false
    end
  end

  refine ::String do
    def blank?
      BLANK_RE === self
    end
  end
end