Writing Your First Ruby DSL (DSL to generate HTML)

Following this for later…

Ruby/Rails Programming

DSLs are easy to write in Ruby and are an elegant way to solve well-defined problems. This post shows how to build a DSL to generate HTML code without getting into too much detail like some of the other blog posts on this same topic. Here is the desired behavior of the DSL:

The HtmlDsl class is initialized with a block that specifies the nesting of the tags and the content. We’ll start by simplifying the problem and writing a DSL that does not handle nested tags:

When the HtmlDsl class is initialized, instance_eval(&block) is run, which executes the block in the context of the newly created instance. The first line of the block calls the method :h1 with the argument ‘h1 body’. The HtmlDsl class does not define a h1 method, so method_missing() is called. In method_missing(), the name parameter equals the name of the method that was called…

View original post 120 more words

Advertisements

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