RSS
27 Nov 2007

Ruby DSL Blocks: A Common Pattern For Developing DSL

Author: ceefour | Filed under: Cool, Opinions, Rails, Reviews, Ruby, Tips, Tools, Web 2.0

There’s a common pattern for developing DSL (Domain Specific Language) in Ruby. It’s used in RSpec, the Statemachine Gem, and Unclebob’s Clean Code talk at RailsConf 2007. The name for this pattern is the DSL Block Pattern.

RSpec

describe "Bowling Game" do
    it "should score 0 on a gutter game" do
        game = Game.new
        20.times { game.roll(0) }
        game.score.should eql(0)
    end
end

Statemachine

sm = Statemachine.build do
trans :locked, :coin, :unlocked
trans :locked, :pass, :locked
trans :unlocked, :pass, :locked
trans :unlocked, :coin, :unlocked
end

Parser

parser = Args.expect do
    boolean "l"
    number "p"
    string "d"
end

You’ve got to write code for specific domain such as writing specifications (RSpec), defining a Statemachine, or defining command line arguments (Unclebob’s Clean Code talk). These domains have a contained and well defined terminology set. Often the cleanest, most elegant way to express this code is to create a DSL.

We can see that the Order object is doing all the work. It’s got the responsibility of interpreting the DSL, so let’s call it the Interpreter Object. The Module::order method simply creates an instance of Order and calls istance_eval on it. This causes the block to execute using the binding of the Order instance. All of the methods on Order will be accessible to the block.

For more information, read Ruby DSL Blocks article by Micah.

No related posts.

Related posts brought to you by Yet Another Related Posts Plugin.

  • http://www.sameshirteveryday.com/2007/12/01/morning-brew-83-2/ Morning Brew #83

    [...] Ruby DSL Blocks: A Common Pattern For Developing DSL [...]

  • http://www.dreamprojections.com/blog/?p=158 Alex Gorbatchev » Morning Brew #89

    [...] Ruby DSL Blocks: A Common Pattern For Developing DSL [...]