From: Robert Klemme Date: 2011-11-29T22:56:28+09:00 Subject: Re: Loading a faulty ruby file - forcing this On Tue, Nov 29, 2011 at 11:38 AM, Marc Heiler wrote: > Hi. > > Consider you have two ruby files. > > file1.rb: > --------------------------------------------------- > require 'pp' > RUBY_FILE = './file2.rb' > > begin >  load RUBY_FILE > rescue NameError => error >  # pp error # Do not report the error here. Be silent. > end > > # Now we call the two methods defined in file2.rb > foo() > bar() > --------------------------------------------------- > > file2.rb: > --------------------------------------------------- > > def foo >  puts 'This is from foo()' > end > > # Create an error on purpose here. > joe_doe() > > def bar # The second method. >  puts 'This is from bar()' > end > --------------------------------------------------- > > Note - I use the parens () at bar() to make it more > explicit and illustrate my question. > > If you run file1.rb, an error occurs: > > undefined method `bar' for main:Object (NoMethodError) > > > The method call to foo() works. > > If you look at the content of file2.rb, you can see that > the method definition first has foo(), then a method > call to a method that does not exist (on purpose), and > then the method definition to bar() > > Ruby apparently stops processing file2.rb when it > encounters a NameError exception. Of course. An exception always immediately stops execution at the point where it is thrown and unwinds the stack until it finds a handler (or the process terminates). > My question is: > > - Is there a way to force or otherwise cause Ruby to continue > reading the second file? I am in control of the ruby files so > I can use eval without a problem. Basically you could wrap every individual section with "begin rescue end". Then such a section would be the smallest part which could fail. Alternatively you could split the file in multiple parts and have a specific implementation of "load" which ignores errors: def load_ignorant(s) load(s) rescue Exception # eat it end > What I would like to achieve is to let ruby read a file > and treat it as a ruby file, but if it encounters errors, > it would disregard these errors, and continue processing > them. > > In a way, I'd need a faulty ruby loader that ignores errors > when instructed. > > Right now, in the code above, I can not achieve this, as > ruby stops the very moment it encounters an invalid method > call. How could I continue to process that faulty file? Why do you want to do that? That sounds like a bad plan to me since you won't notice any issues and your application's state is unclear. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/