ruby · level 3 · unit 5 · lesson 2
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
A collects settings from bare words.
Real apps often read their settings from a DSL, such as name "Corner Shop" and port 8080. Behind it sits a builder: an object whose only job is to collect instructions and then hand back a finished result. Each bare word is a method on the builder that stores one setting.
Good builders start from sensible defaults, so the block only has to say what is different. Here define_method writes one storing method per setting, and instance_eval runs the caller's block on the builder. The finished settings come back as a plain hash.
class SettingsBuilder
attr_reader :settings
def initialize(&block)
@settings = { port: 3000, debug: false }
instance_eval(&block)
end
[:name, :port, :debug].each { |key| define_method(key) { |value| @settings[key] = value } }
end
app = SettingsBuilder.new do
name "Corner Shop"
port 8080
end
p app.settings The person writing the block never sees the builder, only the words it understands.
guess first
Defaults plus two extras. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
class CoffeeOrder
def initialize(&block)
@details = { size: "medium", extras: [] }
instance_eval(&block)
p @details
end
def extra(item)
@details[:extras] << item
end
end
CoffeeOrder.new do
extra "oat milk"
extra "syrup"
end
your turn
Your turn. Set up a game with the DSL.
Type a player name in the first blank and a number of lives in the second. The level keeps its default.
fix it
The shop should run on port 8080. Fix the settings block.
- The name was stored, but the port is still 3000. What is different about line 11?
port = 8080makes a new local variable calledport. It never calls the builder's method.- Write
port 8080, with no equals sign, then press run.
nailed it
you built a builder for your own dsl. :D
- A builder collects settings and hands back a finished result.
- Start from defaults, so the block only says what changes.
- Inside a DSL, write
port 8080, neverport = 8080.
new words in your collection
- builder
This lesson isn’t saved. A free account remembers every lesson you finish.