Skip to content

Instantly share code, notes, and snippets.

@mxriverlynn
Created August 18, 2010 17:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mxriverlynn/535559 to your computer and use it in GitHub Desktop.
Save mxriverlynn/535559 to your computer and use it in GitHub Desktop.
# 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