Alpha Hydrae

Coding on the edge of the web...

Ruby Configuration DSL

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

1
2
3
4
5
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
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:

1
2
3
4
5
# Location: /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:

1
2
3
4
5
6
class MyClass

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

See this article for a more complete version. Take look at Ruby’s BasicObject for the original documentation.

Comments