Skip to content

Type-safe builders (DSLs)

Ruby is famous for DSLs: routes files, build scripts and test suites that read almost like prose. Most of them rely on instance_eval, which runs a block with a different self. That’s powerful, and it also means nobody, least of all your editor, knows what methods are available inside the block until the code runs.

Amethyst keeps the syntax and adds the types. A receiver block declares what self is inside the block, so the compiler can check every call in it. Kotlin calls these type-safe builders; Amethyst calls them receiver blocks; your users will call them “nice”.

By the end of this guide, this will compile and print some HTML:

page = html do
h1 "Shopping list"
ul do
li "Eggs"
li "Milk"
li "Something nice for Friday"
end
end

A builder is an ordinary class. Its methods are the words of your DSL:

html_builder.am
class HtmlBuilder
def initialize
@parts = [] of String
end
def text(content: String): Void
@parts << content
end
def to_s: String
@parts.join("")
end
end

A method declares a receiver block with with, after the block’s signature. Here, () -> Void with HtmlBuilder means “a block with no arguments and no result, where self is an HtmlBuilder”:

def html(&block: () -> Void with HtmlBuilder): String
builder = HtmlBuilder.new
yield builder
builder.to_s
end

For a receiver block, the first value passed to yield becomes self inside the block. So in this code, text is builder.text:

page = html do
text "Hello" # self is the HtmlBuilder, so this is builder.text("Hello")
end

And this doesn’t compile, because HtmlBuilder has no txet:

page = html do
txet "Hello" # compile error: method 'txet' not found on 'HtmlBuilder'
end

That error is the whole point. In Ruby, you’d find out in production, from a user, at an inconvenient hour.

Methods on the builder can take receiver blocks too. That’s what lets a DSL nest:

class HtmlBuilder
# ...
def tag(name: String, &block: () -> Void with HtmlBuilder): Void
@parts << "<#{name}>"
yield self
@parts << "</#{name}>"
end
def h1(content: String): Void
tag("h1") { text content }
end
def ul(&block: () -> Void with HtmlBuilder): Void
tag("ul", &block)
end
def li(content: String): Void
tag("li") { text content }
end
end

yield self passes the same builder down, so the nested block can use every method the outer one can. And because blocks are just blocks, ordinary code works inside them:

groceries = ["Eggs", "Milk", "Something nice for Friday"]
page = html do
h1 "Shopping list"
ul do
groceries.each { |item| li item }
end
end

A nested block can have a different receiver, which restricts what’s available inside it. This is how the Blocks and Closures example stops you putting a title in the body:

class PageBuilder
def head(&block: () -> Void with HeadBuilder): Void
yield HeadBuilder.new # inside: title, meta, link…
end
def body(&block: () -> Void with BodyBuilder): Void
yield BodyBuilder.new # inside: h1, p, ul… but no title
end
end

A receiver block can also take ordinary arguments. The receiver comes first in yield, followed by the arguments:

def table(rows: Array[Product], &block: (Product) -> Void with RowBuilder): Void
rows.each do |product|
yield RowBuilder.new, product
end
end
table(products) do |product|
cell product.name
cell product.price.to_s
end

The type (Product) -> Void with RowBuilder reads as “takes a Product, returns nothing, and runs with a RowBuilder as self”.

Once you know the pattern, you’ll see it all over this site:

DSL Receiver
Routes in config/routes.am Veins::Router
Migrations: create_table :posts do … end Strata::TableBuilder
Configuration in config/database.am Rocks::Configuration
Project files: project :my_app do … end The project configuration
  • Keep builder methods small. Each one is a word in your language, not a sentence.
  • Return the result from the outer method, not from the block. Blocks in a DSL usually return Void, and the builder collects what they describe.
  • Name things for the reader. li "Milk" is a DSL. add_list_item_element("Milk") is a cry for help.