Ruby and Internal DSLs

 Dec, 30 - 2008   13 comments   Ruby

A Domain-specific language(DSL) is a computer language that’s targeted to a particular kind of problem, rather than a general purpose language that’s aimed at any kind of software problem. Domain specific languages have been talked about, and used for almost as long as computing has been done. Regular expressions and CSS are 2 examples of DSLs.

Any software language needs a parser and an interpreter(or compiler or a mix), but in DSLs, we have 2 types: external ones which need parsers and interpreters, and internal ones which rely on the hosting language power to give the feel of a particular language, and thus they don’t require their own parsers.

Ruby is a very convenient language for writing internal DSLs, it has several powerful techniques that enables you easily to write internal DSLs, and many famous products that we use are nothing but internal DSLs: Haml, Builder and Rake .

Lemme show you a very simple example on how an internal DSL might look like using ruby:

As you can tell, this is a very basic internal DSL, written to describe basic tasks for a robot.
There is one task at the moment called ‘stack’ where the robot should do 2 things: fetch the box, and then package it.
Several ruby techniques are used to bring this basic DSL:
1- Blocks: everything between ‘do .. end’ keywords.
2- Parenthesesless methods: like ‘lock’ and ‘seal’.
3- Passing hash values as method arguments without the need of using curly braces: like doing ‘pick :speed => ‘slow’,:height => 15′.

Now all i need is a simple functionality to execute this simple internal DSL:

And the output:

In addition to the 3 points we mentioned earlier, another 2 ones should be added, as they are the heart of the above executer:

4- Reflection techniques: the one we used inside the class method ‘start’, exactly this line “new.instance_eval(&block)”.
5- method_missing: all undefined methods are received by ‘execute’, the alias of method_missing.

As i mentioned earlier, this is a very basic internal DSL, if you are looking for an advanced article covering a more advanced one, then don’t hesitate to check this rich one by Daniel Spiewak.


Related articles