Ruby Configuration DSL

programming Ruby ruby dsl

I had been wondering how that kind of Ruby magic works for some time.

MyClass.new.configure do
  name "the best class"
  purpose "to kick ass"
  tags "ruby", "configuration", "dsl"
end

You have to be willing to use the nasty sounding instance_eval method. It’s scary but trivial:

def MyClass

  def configure &block
    # The block will be called with the
    # MyClass instance as self.
    instance_eval &block
  end

  def name value
    @name = value
  end

  def purpose value
    @purpose = value
  end

  def tags *args
    @tags = args
  end
end

Note that you can also make your own DSL configuration file (like unicorn) using the same technique:

# File: /my/project/config.rb
name "my configuration"
purpose "to look prettier than YAML"
tags "ruby", "configuration", "dsl"

Add this method to the above class to load it:

class MyClass

  def configure_from_file config_file
    instance_eval File.read(config_file), config_file
  end
end

See Ruby DSLs: instance_eval with delegation for a more complete take on this. Take look at Ruby’s BasicObject class for the original documentation.