File: active_support/core_ext/object/blank.rb

Overview
Module Structure
Class Hierarchy
Code

Overview

Module Structure

  module: <Toplevel Module>
  module: <Built-in Module>
  class: Array#58
  class: NilClass#40
inherits from
  Object ( Builtin-Module )
has properties
method: blank? #41
  class: FalseClass#46
inherits from
  Object ( Builtin-Module )
has properties
method: blank? #47
  class: TrueClass#52
inherits from
  Object ( Builtin-Module )
has properties
method: blank? #53
  class: Numeric#72
  class: Hash#62
  class: String#66

Class Hierarchy

Object ( Builtin-Module )
  Array    #58
  NilClass    #40
  FalseClass    #46
  TrueClass    #52
  Numeric    #72
  Hash    #62
  String    #66

Code

   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