From 0da4367c173b139bfe653df9defdfb927541da45 Mon Sep 17 00:00:00 2001 From: Ryan Angilly Date: Thu, 29 Jan 2009 00:15:37 -0500 Subject: [PATCH] adding or_if_blank.rb and test --- .../lib/active_support/core_ext/or_if_blank.rb | 19 +++++++++++++++++++ activesupport/test/core_ext/or_if_blank_test.rb | 13 +++++++++++++ 2 files changed, 32 insertions(+), 0 deletions(-) create mode 100644 activesupport/lib/active_support/core_ext/or_if_blank.rb create mode 100644 activesupport/test/core_ext/or_if_blank_test.rb diff --git a/activesupport/lib/active_support/core_ext/or_if_blank.rb b/activesupport/lib/active_support/core_ext/or_if_blank.rb new file mode 100644 index 0000000..0ebc311 --- /dev/null +++ b/activesupport/lib/active_support/core_ext/or_if_blank.rb @@ -0,0 +1,19 @@ +class Object + # This simplifies cases where you want to do: + # + # self.email.blank? ? self.name : self.email + # + # you can now do: + # + # self.email.or_if_blank self.name + # + # It will work on any object that implements blank? + + def or_if_blank(val) + if respond_to? :blank? + self.blank? ? val : self + else + self + end + end +end diff --git a/activesupport/test/core_ext/or_if_blank_test.rb b/activesupport/test/core_ext/or_if_blank_test.rb new file mode 100644 index 0000000..240bc6b --- /dev/null +++ b/activesupport/test/core_ext/or_if_blank_test.rb @@ -0,0 +1,13 @@ +require 'abstract_unit' + +class OrIfBlankTest < Test::Unit::TestCase + BLANK = ["", [], {}, nil, false] + NOT = ["a", [1,2], {:a => 2}, true, 0] + + def test_or_if_blank + substitute = "substitute me!" + + BLANK.each { |v| assert_equal v.or_if_blank(substitute), substitute } + NOT.each { |v| assert_equal v.or_if_blank(substitute), v } + end +end -- 1.5.4.3 From 4f69395c02bffeadf978b154ca1ad9e3a57376e0 Mon Sep 17 00:00:00 2001 From: Ryan Angilly Date: Thu, 29 Jan 2009 00:25:14 -0500 Subject: [PATCH] Adding tests for case where object does not respond to blank --- activesupport/test/core_ext/or_if_blank_test.rb | 10 ++++++++++ 1 files changed, 10 insertions(+), 0 deletions(-) diff --git a/activesupport/test/core_ext/or_if_blank_test.rb b/activesupport/test/core_ext/or_if_blank_test.rb index 240bc6b..e5fb785 100644 --- a/activesupport/test/core_ext/or_if_blank_test.rb +++ b/activesupport/test/core_ext/or_if_blank_test.rb @@ -1,5 +1,9 @@ require 'abstract_unit' +class NoBlank + undef blank? +end + class OrIfBlankTest < Test::Unit::TestCase BLANK = ["", [], {}, nil, false] NOT = ["a", [1,2], {:a => 2}, true, 0] @@ -10,4 +14,10 @@ class OrIfBlankTest < Test::Unit::TestCase BLANK.each { |v| assert_equal v.or_if_blank(substitute), substitute } NOT.each { |v| assert_equal v.or_if_blank(substitute), v } end + + def test_when_blank_not_defined + a = NoBlank.new + assert !a.respond_to?(:blank?) + assert_equal a.or_if_blank("string"), a + end end -- 1.5.4.3