Ruby DSL's vs YAML vs XML

by: Marcus Ahnve | posted: May 14th, 2007

I am using Ruby based DSL’s for a number of tasks in my current project. But one day it struck me - am I using the right tool for the job, could there be a better, more simple solution?

Some DSL’s I use are simply declarative and look something like this:

 1 quiz "Let's ask stuff" do
 2   question "What is 1+1?" do
 3     alternative "2", :correct => true
 4     alternative "3"
 5   end
 6   question "Vad is 2+3" do
 7     alternative "1"
 8     alternative "Infinity"
 9     alternative "Don't know"
10     alternative "5", :correct => true
11   end
12 end

I find that quite readable, but it requires me to maintain code that handle the DSL. So I figured, what if I used YAML? It is simple, and using it would mean less code to maintain.

After doing some experimenting, this is what I came up with:

 1 quiz: Let's ask stuff
 2 questions:
 3   -
 4     question: What is 1+1 
 5     alternatives:
 6       -
 7         text: 2
 8         correct: true
 9       - 
10         text: 3
11   -
12     question: What is 2+3
13     alternatives:
14       -
15         text: 1
16       -
17         text: "Infinity"
18       -
19         text: "Don't know"
20       -
21         text: 5
22         correct: true

In my opinion, the YAML is not as readable as the Ruby DSL. I also find it more error prone as those dashes are sort of tricky.

XML?

 1 <quiz name="Let's ask stuff">
 2 <questions>
 3   <question text="What is 1 +1"> 
 4     <alternatives>
 5       <alternative correct="true">2</alternative>
 6       <alternative>3</alternative>
 7     </alternatives>
 8   </question>
 9   <question text="What is 2+3">
10     <alternatives>
11       <alternative>1</alternative>
12       <alternative>Infinity</alternative>
13       <alternative>Don't know'</alternative>
14        <alternative correct="true">5</alternative>
15     </alternatives>
16   </question>
17 </questions>
18 </quiz>

With the correct schema, errors can be avoided, but it is just too much text in there, it gets heavy and verbose.

The verdict was to stay with the Ruby DSL’s - their readability and flexibility are well worth the effort of maintaining a separate parser - which is quite short really.