views:

184

answers:

4

Groovys' NodeBuilder uses

def someBuilder = new NodeBuilder()

someBuilder.people(kind:'folks', groovy:true) {
  person(x:123,  name:'James', cheese:'edam') {
    project(name:'groovy')
    project(name:'geronimo')
  }
  person(x:234,  name:'bob', cheese:'cheddar') {
    project(name:'groovy')
    project(name:'drools')
  }
}

whereas Rails' XmlMarkup uses

xm = Builder::XmlMarkup.new
xm.instruct!                   # <?xml version="1.0" encoding="UTF-8"?>
xm.html {                      # <html>
  xm.head {                    #   <head>
    xm.title("History")        #     <title>History</title>
  }                            #   </head>
  xm.body {                    #   <body>
    xm.comment! "HI"           #     <! -- HI -->
    xm.h1("Header")            #     <h1>Header</h1>
    xm.p("paragraph")          #     <p>paragraph</p>
  }                            #   </body>
}                              # </html>

Why is it that with Rails you need to use an explicit receiver (xm) whereas with Groovy you can ommit it? I've heard about the dislike for instance_eval in ruby, why is it groovy can get away with this style whereas ruby can't?

Thanks fractious, just finished reading that article, it's a superb roundup of the different techniques you can use for building DSLs in ruby. I'd vote you up but no rep yet.

+1  A: 

The two libraries have different syntax because they are different libraries, implemented in different languages by (as far as I know) different people, who had similar, but different ideas about how to go about implementing a DSL for writing (amongst other things) XML documents.

Or to put it another way, they're different because they are. I don't know a better way to put it.

It's worth noting that the Builder library is not specifically related to Rails: it's a library implemented as a Ruby Gem and can be used anywhere Ruby is, not just in Rails.

Mike Woodhouse
A: 

There's no reason you couldn't do it that way in Ruby. The author of that library simply didn't.

Chuck
+2  A: 

Here's a good blog post explaining the different ways you might go about implementing a DSL in ruby and the pros and cons of each approach.

fractious
+1  A: 

There is no one answer for this, it's a matter of taste, nothing more. If you are asking whether Groovy's dsl could be done in Ruby, then yes you can using method_missing.

khelll