Dheeraj Kumar

Ruby, Golang, Scala, Javascript

Beautiful DSLs in Ruby - the One Where It All Began

| Comments

At Bang The Table, I work on our flagship product EngagementHQ. Six months ago, I rewrote its entire reporting section, that provides valuable analytics for community managers.

One of the main goals I set for myself here was to split up the concerns – I wanted a set of modules that would provide standalone, testable methods which extract individual pieces of data from the database, and a nice DSL that wraps around them to generate a report.

A week later, each report had gone from an untestable spaghetti of ActiveRecord and Enumerables to this:

1
2
3
4
5
6
7
8
9
10
11
12
class Reports::UsersReport < Reports::BaseReport
  def generate
    report do
      registered do
        users          :users_count
        visits         :visits_count
        median         :visits_per_user_median
        data           :visits_per_user_counts_with_login
      end
    end
  end
end

This DSL generates a hash, with the keys being the methods called, and values are populated by the methods specified by the symbol.

At the Bangalore Ruby User Group meetup in May 2013, I presented a talk on writing DSLs for beginners. I always prefer a live coding session to one with slides, so that’s what I did – built a DSL right there. Deepak Kannan called me a “ballsy bastard” for that.

Comments