
-----------------------------------
wtd
Thu Dec 01, 2005 4:52 am

DSLs
-----------------------------------
Time for a quick look at the power of Ruby to make your life easier.

The term of the day is "Domain Specific Language."  Within a language's rules, we create a sub-language geared specifically toward solving one problem, as easily as possible.

The example problem is one programmers face on a regular basis in the course of learning.  At some point you'll want to create a menu with various options.  We could write the code out each time, but that gets tedious.

class Question
   def self.option(option_text, &response)
      self.class_eval do
         if c = instance_variable_get("@count")
            instance_variable_set "@count", c + 1
         else
            c = 0
            instance_variable_set "@count", c + 1
         end           
      
         if q = instance_variable_get("@options")
            q ||= 

Ok, that didn't look too much better.  Fortunately it's a one time pain, and now when we want to create a menu...

class Q < Question
   question "Foo?"
   
   default_option "foo"
   option "bar"
   option "baz"
   
   on_select { |i, o| puts o }
   
   error_message "Pick another"
end

Q.new.ask

And we end up with:

Foo?

1. foo
2. bar
3. baz
[1] 2
bar

Any questions?  :)
