Dynamic Language Syntax


It’s late and I’m working on my 2nd Budweiser (16oz cans). I got no business posting some in depth technical artical. But I gotta tell you how easy it is to build a dynamic language with Groovy. Tonight I took literally 10 minutes to build a basic GSpec like example using the ExpandoMetaClass in Groovy 1.5. I know you don’t know what an expando meta class is. Neither do I. I just grabbed the example from the docs on the Groovy site and ran with it.

In this example I’m adding methods at runtime to a BarPatron object. The net result is an oogly behavior test that specifies that if you set a BarPtron’s favorite drink to a value then that value should be what you set it to. No lie, I put this together in 15 minutes after 2 Buds. And it’s now 11:25pm!

class BarPatron {
    def favoriteDrink
}

BarPatron.metaClass.invokeMethod = { String name, args ->
    if(name.toLowerCase().endsWith("shouldbe")) {
        def propertyName = name.substring(0, name.toLowerCase().indexOf("shouldbe"))
        assert args[0] == BarPatron.metaClass.getMetaProperty(propertyName).getProperty(delegate)
        return
    }
    def metaMethod = BarPatron.metaClass.getMetaMethod(name, args)
    def result
    if(metaMethod) result = metaMethod.invoke(delegate,args)
    else {
       result = "bar"
    }
    result
}

obj = new BarPatron()
obj.favoriteDrink = 'Bud Light'
obj.favoriteDrinkShouldBe 'Bud Light'

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 250 other followers

%d bloggers like this: