Feb 21 2007

A Very Simple Ruby DSL Example

Published by Chris McAvoy at 10:57 am under Blog, Ruby

Last night at the Perl Monger’s meeting, I showed some code I’ve been working on at work that implements a basic Ruby domain specific language. I pulled the basic concept together this morning and put it into my subversion repository here.

Building your own little mini-language is all the rage, and it ends up being pretty fun to do. However, finding simple examples can be tough. The example in my repository implements what Jamis Buck refers to as Sandboxing.

A runner script opens the file with instructions written in your mini-language, and eval’s it in the context of your DSL class. My example is of the “hello” language. You can save this to the file hellodsl_example:

…execute ./hellodsl_runner.rb hellodsl_example, and get this as a result:

Hello there Chris
Hello there Camri
Hello there Cotton
Hello there Tulip

The magic happens in the HelloDsl class:

When you initialize the class, you pass it the text of your dsl file. The text is eval’d. So you text becomes a series of method calls within the context of the HelloDsl class. The class instance, in Jamis’ explanation, becomes a sandbox in which your code is executed.


Share and Enjoy:
These icons link to social bookmarking sites where readers can share and discover new web pages.

  • del.icio.us
  • digg
  • Reddit
  • StumbleUpon

Trackback URI | Comments RSS

Leave a Reply