Thursday, October 20, 2016

Blank? in Ruby On Rails

The blank? method (a clever Rails extension for those of us too lazy to figure out what type of object we are testing is) is some very smart code:

[7] pry(#<#>)> nil.blank?
=> true
[8] pry(#<#>)> "".blank?
=> true
[9] pry(#<#>)> [].blank?
=> true
[10] pry(#<#>)> {}.blank?
=> true
[11] pry(#<#>)> find-method blank?
[12] pry(#<#>)> show-source blank?

From: /home/saracarl/.rvm/gems/ruby-2.2.0-preview2/gems/activesupport-4.1.2/lib/active_support/core_ext/object/blank.rb @ line 16:
Owner: Object
Visibility: public
Number of lines: 3

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

Let's break it down
respond_to?(:empty?) ?
  if the object has a method called empty?
  return the results of empty?, "not"-ed twice.  This means if the response to emtpy? is "true" it will return true (!(!true)).  If the response is false it will return false (!(!false))  If the response is "nil" it will return false (!(!nil)).  It covers the case where empty? returns nil instead of true or false -- if the object.empty? is nil, then the object.blank? is false
: !self
Else return !self -- if self is nil, return true, otherwise return false.

No comments: