Skip to content

Instantly share code, notes, and snippets.

@phoet
Created June 28, 2009 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phoet/137321 to your computer and use it in GitHub Desktop.
Save phoet/137321 to your computer and use it in GitHub Desktop.
nil-or example
# Creates an object you can savely traverse without getting nil.
# This is very pleasant for deep data-structures.
# You can punch the duck until it should become a string:
# NilOr.new(nil).what.the.fuck?.to_s --> nil
class NilOr
def initialize(object, parent = nil)
@object = object
@call_stack = (parent || [])
puts "current stack #{@call_stack}"
end
def method_missing(sym,*args, &block)
ret = @object.send(sym, *args, &block) unless @object.nil?
NilOr.new(ret, @call_stack.dup << sym)
end
def to_s
@object.to_s
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment