# # # # # # # # #
# /26/catch_nil.rb
#
# by               Jan Lelis
# e-mail:          mail@janlelis.de
# type/version:    ruby 
# snippet url:     http://rbJL.net/26/catch_nil.rb
# original post:   http://rbJL.net/26-the-28-bytes-of-ruby-joy
# license:         CC-BY (DE)
#
# (c) 2010 Jan Lelis.

# Egocentric nil
# code by Yohan, slightly edited and comments by me

# start ego mode block, usage:
# catch_nil do
#   if @some_hash[:some_key].to_formatted_array[3]
#     # do something
#   end
# end
def catch_nil(&block)
  # grip methods
  ori_method_missing   = NilClass.instance_method(:method_missing)
  catch_method_missing = NilClass.instance_method(:catch_method_missing)
  # activate ego mode
  NilClass.send :define_method, :method_missing, catch_method_missing
  # run code
  yield
ensure
  # no matter what happens: restore default nil behaviour
  NilClass.send :define_method, :method_missing, ori_method_missing
end
#alias :egonil :catch_nil # ;)

# this is the ego nil
class NilClass
  def catch_method_missing(m, *args, &block)
    nil
  end
end