Created
August 18, 2010 17:46
-
-
Save mxriverlynn/535559 to your computer and use it in GitHub Desktop.
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
# in ruby, nil is an instance of NilClass. we're monkeypatching NilClass at this point, which is a bad idea for a production app. | |
# but for this example, it gets the point across and should help you find a solution to what you want... maybe... | |
class NilClass | |
def method_missing(name, *args) | |
if respond_to? name | |
return name(*args) | |
else | |
puts "do something about #{name} being nil, here" | |
# this will forward the call to the original NilClass.method_missing | |
# which will raise the standard "undefined method ..." exception | |
# commented out for now, to show you can prevent the error | |
# super name, *args | |
end | |
end | |
end | |
class X | |
attr_accessor :y | |
end | |
class Y | |
attr_accessor :z | |
end | |
class Z | |
attr_accessor :foo | |
end | |
require 'ostruct' | |
somex = X.new | |
somex.y = Y.new | |
somex.y.z = "this is the value of z in somex.y.z" | |
anotherx = X.new | |
anotherx.y = nil | |
puts somex.y.z | |
puts anotherx.y.z | |
puts anotherx.y.z.a.b.c | |
# ... there may be a way to do what you want in a more elegant manner. i don't know off-hand, though. | |
# hope this helps a little, at least. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment