public
Created

  • Download Gist
nilchecks.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
# 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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.