I have noticed that the default way eval, instance_eval(String) and module_eval(String) almost never does what you want unless you supply positioning information. Oh, it will execute all right, and provided you have no bugs in your code, everything is fine. But sooner or later you or someone else will need to debug the code in that eval. In those cases it’s highly annoying when the full error message is “(eval):1: redefining constant Foo”. Sure, in most cases you can still get all the information. But why not just make sure that everything needed is there to trace the call?
I would recommend changing all places you have eval, or where using instance_eval or module_eval that takes a string argument, into the version that takes a file and line number:
eval("puts 'hello world'")# becomeseval("puts 'hello world'", binding, __FILE__, __LINE__)
"str".instance_eval("puts self")# becomes"str".instance_eval("puts self", __FILE__, __LINE__)
String.module_eval("A=1")# becomesString.module_eval("A=1", __FILE__, __LINE__)
Tags: Code, Ruby















No user commented in " Ruby antipattern: Using eval without positioning information "
Follow-up comment rss or Leave a TrackbackLeave A Reply