I’m trying to create “autorequire” for a package, namely if Ruby encounters an unknown constant it tries to require it, and continues where it left off if the require succeeds. Now I have something like this:
def autoload(&block)
yield
rescue NameError => e
if e.message[/constant/]
require e.name.to_s.downcase rescue LoadError raise
retry
end
raise
end
So if I use this like
autoload {
print "Hello, "
x = ArrayFields.new
x << "World!"
puts x[0]
}
As expected, it will print Hello, Hello, World!. So it handles the requiring of the constant, but executes the entire given block from the beginning. So how do I skip to where the fail occurred? This is mostly for academic interest, so I’m also interested in any dangers in attempts like this.
It is not possible to jump back to the point right before the exception from a rescue-clause. A more feasible approach to do what you want would be to override
const_missing.