Skip to content

Instantly share code, notes, and snippets.

@jduff
Created February 15, 2009 19:33
Show Gist options
  • Save jduff/64824 to your computer and use it in GitHub Desktop.
Save jduff/64824 to your computer and use it in GitHub Desktop.
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
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