-
7
OCT
2008DSL Block Styles
There's an argument that rages in the Ruby camps: to
instance_eval()
or not toinstance_eval()
. Most often this argument is triggered by DSL discussions where we tend to want code like:configurable.config do width 100 mode :wrap end
You can accomplish something like this by passing the block to
instance_eval()
and changingself
to an object that defines thewidth()
andmode()
methods. Of course changingself
is always dangerous. We may have already been inside an object and planning to use methods from that namespace:class MyObject include Configurable # to get the config() method shown above def initialize config do width calculate_width # a problem: may not work with instance_eval() end end private def calculate_width # the method we want to use # ... end end
In this example, if
width()
comes from a different configuration object, we're in trouble. Theinstance_eval()
will shift the focus away from ourMyObject
instance and we will get aNoMethodError
when we try to callcalculate_width()
. This may prevent us from being able to useConfigurable
in our code.