DSLs

Posts tagged with "DSLs."
  • 7

    OCT
    2008

    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
    end
    

    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()
        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. 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