This post originated from an RSS feed registered with Ruby Buzz
by Obie Fernandez.
Original Post: DSLish Ruby Hacks, the as operator
Feed Title: Obie On Rails (Has It Been 9 Years Already?)
Feed URL: http://jroller.com/obie/feed/entries/rss
Feed Description: Obie Fernandez talks about life as a technologist, mostly as ramblings about software development and consulting. Nowadays it's pretty much all about Ruby and Ruby on Rails.
DSLs often need to support definition of variables to be used later on in the script. I demonstrated the technique in a previous post about business DSLs. My team uses an idiom for defining variables that looks like this:
It occurred to me that there is a way to express that line that reads even more like English.
define acme as sales_rep_fact.brand_code.equals('ACME')
Ah yes, the subtle tweaks I chase in the name of non-programmer friendliness. So in the example, you see that I've ditched the arrow operator in exchange for the word "as".
Worth it? Maybe, maybe not. It took about 5 minutes of jiggery-pokery in IRB to figure out if it was doable. Remember that I still want to give my define method a hash parameter.
class Object
def method_missing(sym, *args, &block)
{sym => args.first}
end
def as(value)
value
end
end
There you have it. I mixed into the Object class for ease of demo'ing. If you were going to do something like this for real, you'd want to add these methods or something like them to the class that parses your embedded DSL script. YMMV and please bear in mind that this whole post is mostly meant to be thought-provoking and inspire you to your own feats of DSLishness.
If you do try out this code, you will notice that the Ruby interpreter bitches and moans about parentheses...
warning: parenthesize argument(s) for future version
Can someone more in the know about future Ruby interpreter internals advise me how worried I should be about needing to use parentheses? Thanks in advance.