I just stumbled upon a little gem called “class_exec” while reading ruby’s Module docs. I don’t know about other developers preferences, but I really really hate eval(). It is fine in JavaScript for creating JSON objects, but apart from that I really do not like it. No matter if is a simple eval, instance_eval or class_eval. Writing code in strings and evaluating it afterwards just seems wrong. It is something which always bothered me.

As it seems kept on using it although there is a much more beautiful solution to the problem. Here is the description of the method:

Evaluates the given block in the context of the class/module. The method defined in the block will belong to the receiver.

So great! Welcome class_exec, good bye class_eval!

I don’t know why I did not find this earlier, but I guess because the web is full of blog posts and code samples which utilize class_eval. And nobody really updated the stuff after ruby 1.8.7 was released and the class_exec method introduced. I guess it is time to change that!