Created
June 28, 2009 17:43
-
-
Save phoet/137321 to your computer and use it in GitHub Desktop.
nil-or example
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
# 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