ruby: instance_eval a file while maintaining file:line in stacktrace?
If I do
def eval_file(file)
instance_eval read(file)
end
Then once something happens in one of the methods / bl开发者_JAVA百科ocks 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?
As you can see from the documentation, BasicObject#instance_eval
(and in fact all the other *_eval
s 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 ofinstance_eval
that takes aString
, 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
精彩评论