Bird
Raised Fist0
Rubyprogramming~10 mins

DSL building patterns in Ruby - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - DSL building patterns
Define DSL class/module
↓
Define methods for DSL keywords
↓
Create instance or context
↓
Evaluate DSL block
↓
Store or process DSL data
↓
Use DSL results
This flow shows how a Ruby DSL is built by defining methods inside a class or module, then running a block in that context to collect or process data.
Execution Sample
Ruby
class GreetingDSL
  def initialize
    @messages = []
  end
  def say(text)
    @messages << text
  end
  def run(&block)
    instance_eval(&block)
    @messages
  end
end

result = GreetingDSL.new.run do
  say "Hello"
  say "World"
end

puts result.inspect
This Ruby code defines a simple DSL to collect greeting messages and then prints the collected messages.
Execution Table
StepActionEvaluationResult
1Create GreetingDSL instanceGreetingDSL.newInstance with empty @messages array
2Call run with blockrun { say "Hello"; say "World" }Executes block in instance context
3Inside block: call say("Hello")say("Hello")@messages = ["Hello"]
4Inside block: call say("World")say("World")@messages = ["Hello", "World"]
5run returns @messagesreturn @messages["Hello", "World"]
6puts result.inspectputs ["Hello", "World"].inspect["Hello", "World"] printed
7EndNo more codeExecution stops
💡 Execution stops after printing the collected messages array.
Variable Tracker
VariableStartAfter Step 3After Step 4Final
@messages[]["Hello"]["Hello", "World"]["Hello", "World"]
Key Moments - 3 Insights
Why does the block inside run use instance_eval?
Using instance_eval runs the block with self as the DSL instance, so calls like say "Hello" call the DSL methods directly (see execution_table steps 2-4).
How does the say method add messages?
The say method appends the given text to the @messages array, updating state step-by-step (see variable_tracker).
What does run return and why?
run returns the @messages array after the block runs, so the collected data is accessible outside (see execution_table step 5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 3, what is the value of @messages after say("Hello")?
A[]
B["World"]
C["Hello"]
D["Hello", "World"]
💡 Hint
Check variable_tracker column 'After Step 3' and execution_table step 3.
At which step does the run method return the collected messages?
AStep 5
BStep 4
CStep 2
DStep 6
💡 Hint
Look at execution_table step 5 where run returns @messages.
If instance_eval was not used in run, what would happen to calls like say "Hello" inside the block?
AThey would call the say method on the DSL instance as expected.
BThey would cause an error because say is undefined in the block's context.
CThey would call a global say method.
DThey would be ignored silently.
💡 Hint
Recall that instance_eval changes self so DSL methods are found (see key_moments question 1).
Concept Snapshot
Ruby DSL building pattern:
- Define a class/module with methods as DSL keywords
- Use instance_eval to run a block in DSL context
- Collect data in instance variables
- Return or process collected data after block
- Enables clean, readable domain-specific code blocks
Full Transcript
This example shows how to build a simple Ruby DSL by defining a class with methods that represent DSL commands. The run method uses instance_eval to execute a block where these DSL methods can be called directly. Each call to say adds a message to an internal array. After the block finishes, the collected messages are returned and printed. The execution table traces each step, showing how the internal state changes and how the block is evaluated. Key moments clarify why instance_eval is needed and how data is collected. The quiz tests understanding of variable changes and method calls within the DSL context.

Practice

(1/5)
1. What is the main purpose of using a DSL (Domain Specific Language) in Ruby?
easy
A. To make code easier to read and write for specific tasks
B. To speed up Ruby interpreter execution
C. To replace Ruby's core syntax completely
D. To automatically generate user interfaces

Solution

  1. Step 1: Understand DSL purpose

    A DSL is designed to simplify and clarify code for a specific domain or task.
  2. Step 2: Compare options

    Only To make code easier to read and write for specific tasks correctly states the purpose of DSLs; others describe unrelated goals.
  3. Final Answer:

    To make code easier to read and write for specific tasks -> Option A
  4. Quick Check:

    DSL purpose = simplify domain code [OK]
Hint: DSLs focus on specific tasks for clearer code [OK]
Common Mistakes:
  • Thinking DSLs speed up Ruby interpreter
  • Believing DSLs replace Ruby syntax entirely
  • Confusing DSLs with UI generators
2. Which Ruby method is commonly used to execute a block inside the context of a DSL object?
easy
A. eval_block
B. block_exec
C. class_eval
D. instance_eval

Solution

  1. Step 1: Recall Ruby block execution methods

    Ruby provides methods like instance_eval and class_eval to run blocks in specific contexts.
  2. Step 2: Identify the method for DSL context

    instance_eval runs the block inside the instance's context, which is typical for DSLs.
  3. Final Answer:

    instance_eval -> Option D
  4. Quick Check:

    Block runs in object context = instance_eval [OK]
Hint: Use instance_eval to run blocks inside DSL objects [OK]
Common Mistakes:
  • Confusing class_eval with instance_eval
  • Using non-existent methods like eval_block
  • Assuming block_exec is a Ruby method
3. What will be the output of this Ruby DSL code?
class Builder
  def initialize
    @steps = []
  end
  def step(name)
    @steps << name
  end
  def build(&block)
    instance_eval(&block)
    @steps
  end
end

b = Builder.new
result = b.build do
  step 'clean'
  step 'compile'
  step 'test'
end
puts result.inspect
medium
A. [:clean, :compile, :test]
B. ["clean", "compile", "test"]
C. ["step", "step", "step"]
D. SyntaxError

Solution

  1. Step 1: Understand the Builder class behavior

    The build method runs the block inside the Builder instance, collecting step names as strings in @steps.
  2. Step 2: Trace the block execution

    Each call to step adds the string name to @steps: 'clean', 'compile', 'test'. The build method returns @steps.
  3. Final Answer:

    ["clean", "compile", "test"] -> Option B
  4. Quick Check:

    Collected steps = ["clean", "compile", "test"] [OK]
Hint: instance_eval runs block adding strings to array [OK]
Common Mistakes:
  • Expecting symbols instead of strings
  • Thinking step method returns step name
  • Confusing array contents with method names
4. Identify the error in this DSL builder code:
class Configurator
  def set(name, value)
    @settings ||= {}
    @settings[name] = value
  end
  def configure(&block)
    instance_eval(block)
  end
end

c = Configurator.new
c.configure do
  set :mode, 'fast'
end
medium
A. Wrong argument passing to instance_eval
B. Missing @settings initialization
C. set method missing return value
D. Block not passed to configure method

Solution

  1. Step 1: Check instance_eval usage

    instance_eval expects a block passed with &block, but here it is called as instance_eval(block) without &.
  2. Step 2: Understand correct block passing

    The correct call is instance_eval(&block) to convert the block argument to a block for instance_eval.
  3. Final Answer:

    Wrong argument passing to instance_eval -> Option A
  4. Quick Check:

    Use &block with instance_eval [OK]
Hint: Pass block with & when calling instance_eval [OK]
Common Mistakes:
  • Calling instance_eval without & for block
  • Forgetting to initialize @settings
  • Expecting set to return a value
5. You want to build a Ruby DSL that allows nested configuration like this:
config = Config.new do
  database do
    adapter 'sqlite3'
    pool 5
  end
  cache do
    enabled true
    size 64
  end
end
Which approach best supports this nested DSL pattern?
hard
A. Use global variables to store settings inside blocks
B. Use class variables to share state across blocks
C. Use instance_eval with separate classes for database and cache blocks
D. Use eval with string interpolation for nested blocks

Solution

  1. Step 1: Understand nested DSL needs

    Nested blocks require separate context objects for database and cache to hold their settings.
  2. Step 2: Identify best practice

    Using instance_eval on separate classes for each nested block cleanly isolates configuration and supports nested DSL.
  3. Final Answer:

    Use instance_eval with separate classes for database and cache blocks -> Option C
  4. Quick Check:

    Nested DSL = instance_eval + separate classes [OK]
Hint: Use instance_eval with helper classes for nested blocks [OK]
Common Mistakes:
  • Using global variables causing conflicts
  • Using class variables mixing state
  • Using eval with strings risking security and complexity
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard