Skip to content
Tutorials Center
My learning

Topics

Lesson 67 of 134 ยท Metaprogramming

Building DSLs

Learn how to design internal DSLs in Ruby with blocks, builder objects, instance_eval and method chaining, with working HTML, route and config examples.

A domain-specific language (DSL) is a small language for one kind of problem. SQL is a DSL for queries, CSS for styles. Ruby is famous for internal DSLs: ordinary Ruby code that is arranged so it reads like its own language. get "/users" do ... end in a web framework, describe "thing" do ... end in a test suite and task :build do ... end in a build file are all plain Ruby method calls with blocks.

Ruby's optional parentheses, blocks, symbols, keyword arguments and instance_eval are exactly the ingredients you need. In this lesson you will build four DSLs from scratch (a configuration, an HTML builder, a route table and a chainable query), learn the design rules that make them pleasant, and see how to give good errors when a user makes a mistake.

The ingredients

Look at this line: server port: 8080, host: "example.test". It is a method call without parentheses, with keyword arguments. And this one: route "/" do ... end is a method call with a block. A DSL author provides the methods; Ruby's flexible syntax does the rest.

  1. Methods with optional parentheses, so calls read like statements.
  2. Blocks, to nest structure (section do ... end).
  3. A builder object that collects what the user declares.
  4. instance_eval / instance_exec to run the user's block with the builder as self, so no builder. prefix is needed (the previous lesson covers this).
  5. Keyword arguments and symbols for options.
  6. Method chaining (each method returns self), for fluent APIs.

DSL 1: a configuration object

The simplest DSL records settings.

Ruby A configuration DSL

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Inside the block, any one-argument "call" becomes a setting through method_missing, and environment adds a prefix while its inner block runs. The ensure clause restores the previous prefix even if the block raises. This style is compact but loose: any typo becomes a new setting. The next versions are stricter.

A method_missing catch-all is the quickest DSL, but it accepts misspellings (retires 3). If the set of options is known, define real methods instead and let unknown names raise NoMethodError.

DSL 2: an HTML builder

A classic. Nested blocks create nested tags, and the builder collects output as it goes.

Ruby A tiny HTML builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Every tag name goes to method_missing, which decides between a tag with content (h1 "Hello") and a tag with children (a block). The indentation depth tracks nesting. Real libraries (Builder, Markaby, Arbre) do the same with more care: they escape text, subclass BasicObject so that tag names like p or select do not collide with Kernel#p and Kernel#select, and define a method for each known tag. Notice that this builder has no way to make a <p> tag: p "hello" finds Kernel#p, which prints to the console and never reaches method_missing. That is the single biggest trap of Object-based builders.

DSL 3: a route table with defined methods

When you know the vocabulary, define real methods. This route DSL accepts only get, post and namespace, and validates what it receives.

Ruby A routing DSL with validation (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The methods are generated with define_method (see that lesson), so a typo such as gett raises a clear NoMethodError, to: is a required keyword (forgetting it gives an ArgumentError), and the path is validated up front. The final call ends the program with main.rb:21:in 'block (2 levels) in <class:Router>': path must start with /: "no-slash" (Router::RouteError), and the next backtrace line, from main.rb:55:in 'block in <main>', points at the get line the user wrote. Errors in a DSL should say what the user did wrong in the user's terms.

DSL 4: method chaining

Not every DSL uses blocks. A fluent interface returns self from each step so calls chain, as in User.where(...).order(...).limit(...).

Ruby A chainable query builder

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

This mutates one object and returns it. Real query builders usually return a new, immutable object from each step (dup then change), so a partial query can be reused safely. The sketch here is only meant to show the shape; never build real SQL by concatenating user input, as this toy does, because of injection risks.

Design rules for DSLs that people like

  1. Start from the usage. Write the code you wish users could write, then make Ruby accept it.
  2. Keep the vocabulary small and consistent. If one option is retries 3, do not make another set_timeout(5).
  3. Prefer defined methods to method_missing. Real methods give clean errors, respond_to?, and documentation.
  4. Give good errors. Check arguments in the DSL methods and raise errors that use the user's words. Include the DSL's own error class (like RouteError).
  5. Offer both styles when practical. Allow a block with a parameter (do |r| r.get ... end) for people who need access to the outer self.
  6. Return values on purpose. Builders return the finished result (a frozen config, a string), not the builder.
  7. Freeze or validate at the end. After the block runs, check required settings and freeze the result so later code cannot change it by accident.
  8. Stay Ruby. A DSL is still a program: loops, conditionals and variables work inside the block, which is a huge feature.
Ruby DSL blocks are real Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The block uses a hash defined outside, iterates it with each, and conditionally adds an item. A DSL built on blocks inherits all of Ruby for free, which configuration files in YAML or JSON cannot match.

Testing and pitfalls

  • Test the DSL like an API. Write examples of valid and invalid usage and check the resulting object and the error messages (see Testing with Minitest).
  • Beware leaking self. In instance_eval blocks, calls to the user's own methods fail; document it, or support the yielded-builder form.
  • Name clashes. Methods from Object/Kernel (p, puts, format, select, display, test) shadow DSL words. Inherit from BasicObject or avoid the words.
  • Debuggability. Because DSL code is plain Ruby, backtraces show the user's block lines. Keep them readable by raising the errors in the DSL methods rather than deep inside helper code.
  • Don't build a DSL when a hash will do. If configuration is a handful of options, Config.new(host: "x", port: 1) is simpler and easier to test.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes a Ruby internal DSL possible?

    An internal DSL is plain Ruby. Its readable shape comes from blocks, optional parentheses, symbols and keyword arguments, with instance_eval removing the explicit receiver.
  2. 2. Why did the HTML builder in this lesson fail to create a <p> tag?

    method_missing is only called when no method is found. Kernel#p is found first. Basing the builder on BasicObject removes these clashes.
  3. 3. Why is a DSL made of defined methods usually better than one built on method_missing?

    With a known vocabulary, real methods give precise errors and documentation, while method_missing accepts any misspelling.
  4. 4. What does a fluent (chainable) method usually return?

    Returning the receiver, or a modified copy, is what lets you write a.where(...).order(...).limit(...).
  5. 5. What is a good practice at the end of a configuration DSL block?

    Validation reports missing options early, and freezing prevents accidental later changes.

Summary

  • An internal DSL is ordinary Ruby arranged to read like a small language, using blocks, optional parentheses, keyword arguments and symbols.
  • A builder object collects declarations; instance_eval (or yielding the builder) runs the user's block against it.
  • Prefer defined methods with validation over method_missing; give clear errors in the user's words.
  • Method chaining returns self or a new copy; immutable copies are safer.
  • Beware names that clash with Kernel methods (p, select), and offer a block-parameter form so users can reach their own self.
  • Validate and freeze the finished result, and do not build a DSL where a plain hash or constructor would do.

Next: Reflection and Introspection