I really like Smalltalk’s ifNil: and ifNotNil:, and up to now, I could not use these in Ruby. Fortunately, Bob Hutchison came to the rescue with A Little Unnecessary Smalltalk Envy.
I immediately copied that to XLsuite and wrote a couple of tests. Here is sample of what the code feels like:
1 >> Party.find_by_email_address("sam@gamgee.net").if_not_nil do |party| 2 ?> puts "Found Sam!" 3 >> end 4 => nil
Oh well, no Sam in my database. The code is here:
test/unit/smalltalk_test.rb
1 require File.dirname(__FILE__) + "/../test_helper" 2 3 class SmalltalkTest < Test::Unit::TestCase 4 setup do 5 @block = Proc.new { true } 6 end 7 8 context "The nil object" do 9 should "yield when calling #if_nil on it" do 10 assert nil.if_nil(&@block) 11 end 12 13 should "not yield when calling #if_not_nil on it" do 14 deny nil.if_not_nil(&@block) 15 end 16 end 17 18 context "A non nil object" do 19 should "not yield when calling #if_nil on it" do 20 deny "".if_nil(&@block) 21 end 22 23 should "yield when calling #if_not_nil on it" do 24 assert "".if_not_nil(&@block) 25 end 26 27 should "pass itself to #if_not_nil" do 28 obj = "abc" 29 assert_same obj, obj.if_not_nil {|o| o} 30 end 31 end 32 end
lib/smalltalk.rb
1 # Copied and adapted from 2 # http://recursive.ca/hutch/2007/11/22/a-little-unnecessary-smalltalk-envy/ 3 # Bob Huntchison 4 class Object 5 # yield self when it is non nil. 6 def if_not_nil(&block) 7 yield(self) if block 8 end 9 10 # yield to the block if self is nil 11 def if_nil(&block) 12 end 13 end 14 15 class NilClass 16 # yield self when it is non nil. 17 def if_not_nil(&block) 18 end 19 20 # yield to the block if self is nil 21 def if_nil(&block) 22 yield if block 23 end 24 end
blog comments powered by Disqus