Floyd’s Thoughts…

Because Everything is Interesting!!!

Something I didn’t know Yesterday #2

without comments

Rails (or should i say ActiveSupport) adds a blank? instance method to object that encapsulates the nil? || empty? check that I find myself doing all the time.

A quick review of the source show that the empty? method is added to the following:

  # An object is blank if it's nil, empty, or a whitespace string.
  # For example, "", "   ", nil, [], and {} are blank.
  #
  # This simplifies
  #   if !address.nil? && !address.empty?
  # to
  #   if !address.blank?

The full source is actually very simple (I Love Ruby)

class Object
 
  def blank?
    if respond_to?(:empty?) && respond_to?(:strip)
      empty? or strip.empty?
    elsif respond_to?(:empty?)
      empty?
    else
      !self
    end
  end
end
 
class NilClass #:nodoc:
  def blank?
    true
  end
end
 
class FalseClass #:nodoc:
  def blank?
    true
  end
end
 
class TrueClass #:nodoc:
  def blank?
    false
  end
end
 
class Array #:nodoc:
  alias_method :blank?, :empty?
end
 
class Hash #:nodoc:
  alias_method :blank?, :empty?
end
 
class String #:nodoc:
  def blank?
    empty? || strip.empty?
  end
end
 
class Numeric #:nodoc:
  def blank?
    false
  end
end

Written by Floyd Price

August 13th, 2008 at 8:46 pm

Leave a Reply

Get Adobe Flash playerPlugin by wpburn.com wordpress themes