Studying the Ruby Docile Gem to Learn About DSLs

Following this for later….

Ruby/Rails Programming

A Stackoverflow user suggests studying the Docile source code to learn how to write DSLs in Ruby, but the source code is dense for programmers new to Ruby DSLs. This blog posts demonstrates how to write a DSL that behaves similarly to the Docile gem, but with much less code.

At a fundamental level, Docile evaluates a block in the context of an object with the instance_eval() method:

The instance_eval() portion can be abstracted to a method as follows:

The dsl() method takes an object and a block as arguments and simply sends the :instance_eval message to the object with the block as an argument.

Suppose there is a Pizza class to make pizzas. The same dsl() method can be used to customize an instance of the Pizza class.

The prior example uses a block variable to avoid implicit self syntax that is interpreted by the Ruby interpreter as local…

View original post 27 more words


Leave a Reply

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

You are commenting using your 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