Class: Object

Inherits:
BasicObject
Defined in:
lib/ruby/blank.rb

Overview

This file is pulled straight from ActiveSupport, MIT-LICENSE copied below for attribution purposes:

Copyright © 2005-2011 David Heinemeier Hansson

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Instance Method Summary collapse

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?

Returns:

  • (Boolean)


35
36
37
# File 'lib/ruby/blank.rb', line 35

def blank?
  respond_to?(:empty?) ? empty? : !self
end

#presenceObject

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'


58
59
60
# File 'lib/ruby/blank.rb', line 58

def presence
  self if present?
end

#present?Boolean

An object is present if it’s not blank?.

Returns:

  • (Boolean)


40
41
42
# File 'lib/ruby/blank.rb', line 40

def present?
  !blank?
end