This is a nice article about the subtleties of instance_eval in Ruby. It's an interesting feature that powers some very clever DSLs [1][2][3].
At the same time it's a feature that is confusing and should be avoided as much as possible. One reason is that it is impossible to predict by looking at the calling code in which context a block is executed if instance_eval is used. Another reason is that a block that is executed with instance_eval cannot reference instance variables of the calling object. No problem for trivial code, but a huge headache for slightly more complex code or for views in Rails apps (which use instance variables to pass objects from controllers to views). And unlike the inability to call local helper methods (as explained at the end in the article) this cannot be worked around by throwing more magic into the mix.
I believe there's some consensus now that instance_eval is a nice trick, but should be reserved for simple DSLs or DSLs that don't interact much with other code. Some libraries [4] have stopped using instance_eval altogether because of associated problems.
If you do use instance_eval in your API, be sure to mention it explicitly in the documentation to avoid headaches for your users.
6 comments
[ 2.6 ms ] story [ 23.0 ms ] threadSimpler languages have fewer edge cases.
At the same time it's a feature that is confusing and should be avoided as much as possible. One reason is that it is impossible to predict by looking at the calling code in which context a block is executed if instance_eval is used. Another reason is that a block that is executed with instance_eval cannot reference instance variables of the calling object. No problem for trivial code, but a huge headache for slightly more complex code or for views in Rails apps (which use instance variables to pass objects from controllers to views). And unlike the inability to call local helper methods (as explained at the end in the article) this cannot be worked around by throwing more magic into the mix.
I believe there's some consensus now that instance_eval is a nice trick, but should be reserved for simple DSLs or DSLs that don't interact much with other code. Some libraries [4] have stopped using instance_eval altogether because of associated problems.
If you do use instance_eval in your API, be sure to mention it explicitly in the documentation to avoid headaches for your users.
[1]:https://github.com/ernie/squeel [2]:http://api.rubyonrails.org/classes/ActionDispatch/Routing.ht... [3]:http://docs.opscode.com/chef/dsl_recipe.html [4]:http://builder.rubyforge.org/classes/Builder/XmlMarkup.html