×

ruby · level 3 · unit 5 · lesson 2

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.