Created
February 15, 2009 19:33
-
-
Save jduff/64824 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Object | |
# Useage: | |
# @user.name.or("blank") | |
# if @user's name is nil or "", returns "blank", otherwise returns the name | |
def or(value) | |
(respond_to?(:empty?) ? empty? : !self) ? value : self | |
end | |
end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require File.dirname(__FILE__) + '/../test_helper' | |
class CoreExtensionsTest < ActiveSupport::TestCase | |
context "or called on an object" do | |
should "should return the object if not nil" do | |
assert_equal "something", "something".or("nothing") | |
assert_equal [1,2], [1,2].or([3,4]) | |
end | |
should "should return the alternative if nil or empty" do | |
assert_equal "nothing", nil.or("nothing") | |
assert_equal "nothing", "".or("nothing") | |
assert_equal [1,2], [].or([1,2]) | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment