From 5239346afe9207849b45a02d1293f6805aa7faec Mon Sep 17 00:00:00 2001 From: Colin Kelley Date: Sat, 26 Dec 2009 16:06:19 -0800 Subject: [PATCH] Added Object#nonblank? (analogous to Numeric#nonzero?) --- .../lib/active_support/core_ext/object/blank.rb | 27 ++++++++++++++++++++ activesupport/test/core_ext/blank_test.rb | 5 +++ 2 files changed, 32 insertions(+), 0 deletions(-) diff --git a/activesupport/lib/active_support/core_ext/object/blank.rb b/activesupport/lib/active_support/core_ext/object/blank.rb index 9a1f663..bd5e8a4 100644 --- a/activesupport/lib/active_support/core_ext/object/blank.rb +++ b/activesupport/lib/active_support/core_ext/object/blank.rb @@ -17,6 +17,33 @@ class Object def present? !blank? end + + # The nonblank? method is analogous to Ruby's Numeric#nonzero?[http://ruby-doc.org/core/classes/Numeric.html#M000186] method. + # + # Returns object unless it's #blank?(), in which case it returns nil: + # object.nonblank? is equivalent to (object.blank? : nil : object). + # + # 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] unless params[:state].blank? + # country = params[:country] unless params[:country].blank? + # region = state || country || 'US' + # + # becomes + # + # region = params[:state].nonblank? || params[:country].nonblank? || 'US' + # + # In general, nonblank? can be used any time you want to map empty? or false + # to nil: + # + # options = { :html => { :style => 'margin: 10;' } } + # other_options = options.except(:html).nonblank? + # => nil + def nonblank? + self unless blank? + end end class NilClass #:nodoc: diff --git a/activesupport/test/core_ext/blank_test.rb b/activesupport/test/core_ext/blank_test.rb index 1dbbf3f..d40dc77 100644 --- a/activesupport/test/core_ext/blank_test.rb +++ b/activesupport/test/core_ext/blank_test.rb @@ -22,4 +22,9 @@ class BlankTest < Test::Unit::TestCase BLANK.each { |v| assert !v.present?, "#{v.inspect} should not be present" } NOT.each { |v| assert v.present?, "#{v.inspect} should be present" } end + + def test_nonblank + BLANK.each { |v| assert_equal nil, v.nonblank?, "#{v.inspect}.nonblank? should return nil" } + NOT.each { |v| assert_equal v, v.nonblank?, "#{v.inspect}.nonblank? should return self" } + end end -- 1.6.4.1