Class: Object
- Inherits:
- BasicObject
- Defined in:
- lib/burr/core_ext/blank.rb
Overview
This file is steal from Rails
Instance Method Summary collapse
-
#blank? ⇒ Boolean
An object is blank if it’s false, empty, or a whitespace string.
-
#presence ⇒ Object
Returns object if it’s
present?
otherwise returnsnil
. -
#present? ⇒ Boolean
An object is present if it’s not
blank?
.
Instance Method Details
#blank? ⇒ Boolean
An object is blank if it’s false, empty, or a whitespace string. For example, ”, ‘ ’, nil
, [], and {} are all blank.
This simplifies:
if address.nil? || address.empty?
…to:
if address.blank?
16 17 18 |
# File 'lib/burr/core_ext/blank.rb', line 16 def blank? respond_to?(:empty?) ? empty? : !self end |
#presence ⇒ Object
Returns object if it’s present?
otherwise returns nil
. object.presence
is equivalent to object.present? ? object : nil
.
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 || 'US'
…becomes:
region = params[:state].presence || params[:country].presence || 'US'
39 40 41 |
# File 'lib/burr/core_ext/blank.rb', line 39 def presence self if present? end |
#present? ⇒ Boolean
An object is present if it’s not blank?
.
21 22 23 |
# File 'lib/burr/core_ext/blank.rb', line 21 def present? !blank? end |