In Ruby, I'd like to catch the NoMethodError generated on an object in another object, then return some value to where the exception is raised and continue execution. Is there an existing way to do this?
The best I came up with is:
class Exception
attr_accessor :continuation
end
class Outer
def hello
puts "hello"
end
class Inner
def world
puts "world"
end
def method_missing(method, *args, &block)
x = callcc do |cc|
e = RuntimeError.exception(method)
e.continuation = cc
raise e
end
return x
end
end
def inner(&block)
inner = Inner.new
begin
inner.instance_eval(&block)
rescue => e
cc = e.continuation
cc.call(hello())
end
inner
end
end
o = Outer.new
o.inner do
hello
world
end
This prints
hello
world
Is there a better way to do this using Ruby's existing array of meta-programming arsenal? Basically, I am not sure if callcc will continue to exist.
Thanks.