Articles Feed

Authors

Categories

Ruby DSL Blocks

by: micah | May 20th, 2007 |

There’s a common pattern I’ve seen for developing DSLs (Domain Specific Language) in Ruby. It’s used in RSpec, the Statemachine Gem, and Unclebob’s Clean Code talk at RailsConf 2007. I haven’t seen a name for this pattern so I’ll call it the DSL Block Pattern.

RSpec

  1. describe "Bowling Game" do
  2. it "should score 0 on a gutter game" do
  3. game = Game.new
  4. 20.times { game.roll(0) }
  5. game.score.should eql(0)
  6. end
  7. end

Statemachine

  1. sm = Statemachine.build do
  2. trans :locked, :coin, :unlocked
  3. trans :locked, :pass, :locked
  4. trans :unlocked, :pass, :locked
  5. trans :unlocked, :coin, :unlocked
  6. end

Parser

  1. parser = Args.expect do
  2. boolean "l"
  3. number "p"
  4. string "d"
  5. end

Here’s the problem. 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.

Before diving into the example, let me say that I like coffee as much as the next guy. But I feel lost when ever I go to a Starbucks. As you know, Starbucks has a it’s own language, DSL if you will, for ordering coffee. What follows is a DSL Block for ordering Starbucks coffee.

The general grammar for ordering coffee is: Size, Adjective (optional), Type of Coffee. This is by no means comprehensive but it’s sufficient for the example. So if you wanted to order a large coffee, for example, you would say, Grande Coffee. A small espresso: Short Americano. An extra large mixture of regular and decaffeinated coffee with some half and half: Venti Breve Half Caff.

Given the task to code these coffee orders, I’d like to be able to code it like this:

  1. Starbucks.order do
  2. grande.coffee
  3. short.americano
  4. venti.breve.half_caff
  5. end

Ok that looks good, but as you look closely, you’ll start to wonder about those methods, grande, short, and venti “Do they have to be defined on the Kernel?” you may ask. Defining them on the Kernel is a scary prospect. And that may convince you to clutter the syntax by passing an object into the block like this:

  1. Starbucks.order do |order|
  2. order.grande.coffee
  3. order.short.americano
  4. order.venti.breve.half_caff
  5. end

This would allow you to define the grande, short, and venti methods on the object passed into the block. Although you do need an object where grande, short, and venti will be defined, you don’t need to add an argument to the block. You’ll find code out there, such as Migrations, that uses this less optimal route. It’s not necessary. The trick to get rid of the argument is below:

  1. module Starbucks
  2. def self.order(&block)
  3. order = Order.new
  4. order.instance_eval(&block)
  5. return order.drinks
  6. end
  7. class Order
  8. attr_reader :drinks
  9. def initialize
  10. @drinks = []
  11. end
  12. def short
  13. @size = "small"
  14. return self
  15. end
  16. def grande
  17. @size = "large"
  18. return self
  19. end
  20. def venti
  21. @size = "extra large"
  22. return self
  23. end
  24. def coffee
  25. @drink = "coffee"
  26. build_drink
  27. end
  28. def half_caff
  29. @drink = "regular and decaffeinated coffee mixed together"
  30. build_drink
  31. end
  32. def americano
  33. @drink = "espresso"
  34. build_drink
  35. end
  36. def breve
  37. @adjective = "with half and half"
  38. return self
  39. end
  40. private
  41. def build_drink
  42. drink = "#{@size} cup of #{@drink}"
  43. drink << " #{@adjective}" if @adjective
  44. @drinks << drink
  45. @size = @drink = @adjective = nil
  46. end
  47. end
  48. end

You 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.

The Interpreter Object can do any number of things as it interprets the DSL. In this case it simply generates a translation for Starbucks newbies. But, the sky’s the limit really.

Show all the source code.

4 Responses to “Ruby DSL Blocks”

  1. Andy Maleh Says:
    Thanks for pointing out that pattern. Great examples. Do you know any other Ruby DSL patterns? Any good references online about building Ruby DSLs in general?
  2. Hendy Irawan Says:
    What a great way to describe a DSL and how to do with it. For now I'm in trouble of interpreting DSLs... I thought simple XMLs are simpler to parse than a Ruby-based DSL. I hope that can change. This is really cool... Very useful stuff, Micah! Great article...
  3. Clinton Forbes Says:
    It takes real talent to take something relatively complex and explain it in such simple terms. Well done. The coffee example was great (even though I can't stand the stuff).
  4. mmorpg Says:
    I enjoyed your analogy on the language being foreign like Starbucks haha...have you seen the new Dunkin Donuts commercial for them btw? good stuff.

Leave a Reply

#