Posts tagged with "DSLs."
  • 7


    DSL Block Styles

    There's an argument that rages in the Ruby camps: to instance_eval() or not to instance_eval(). Most often this argument is triggered by DSL discussions where we tend to want code like:

    configurable.config do
      width 100
      mode  :wrap

    You can accomplish something like this by passing the block to instance_eval() and changing self to an object that defines the width() and mode() methods. Of course changing self 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()
      def calculate_width        # the method we want to use
        # ...

    In this example, if width() comes from a different configuration object, we're in trouble. The instance_eval() will shift the focus away from our MyObject instance and we will get a NoMethodError when we try to call calculate_width(). This may prevent us from being able to use Configurable in our code.

    Read more…

    In: Ruby Voodoo | Tags: DSLs & Style | 7 Comments