Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ruby: instance_eval a file while maintaining file:line in stacktrace?

Tags:

ruby

If I do

def eval_file(file)
  instance_eval read(file)
end

Then once something happens in one of the methods / blocks inside the file all I see is something like (eval):20 in 'eval_file'. When I use eval_file with many files it is hard to tell from which one the exception came (the exception happens after the eval, when using a method)

Is there some way for me to see the actual file and line number?

like image 420
IttayD Avatar asked Jan 12 '11 09:01

IttayD


1 Answers

As you can see from the documentation, BasicObject#instance_eval (and in fact all the other *_evals as well) will simply report whatever file name and line number you tell it to:

Method: BasicObject#instance_eval

  • (Object) instance_eval(string[, filename [, lineno]])

Evaluates a string containing Ruby source code, or the given block, within the context of the receiver (obj). In order to set the context, the variable self is set to obj while the code is executing, giving the code access to obj’s instance variables. In the version of instance_eval that takes a String, the optional second and third parameters supply a filename and starting line number that are used when reporting compilation errors.

[…]

Overloads:

  • (Object) instance_eval(string[, filename [, lineno]])

[Emphasis mine.]

In general, if you use the String overload of the *_eval methods, you should make sure that you get sensible location information by passing file name and line number [alternative link].

In your particular case, you would omit the line number, since you want Ruby to simply use the line number(s) of the file, but you need to pass the file name:

def eval_file(file)
  instance_eval read(file), file
end
like image 50
Jörg W Mittag Avatar answered Sep 19 '22 02:09

Jörg W Mittag