Configuration like the big ones
Many Ruby tools are configured with elegant blocks – that's called a DSL (domain-specific language). The trick behind it is a single method: instance_eval runs a block as if it were written inside the object – self switches:
class Menu
attr_reader :dishes
def initialize
@dishes = {}
end
def dish(name, price:)
@dishes[name] = price
end
end
def menu(&block)
m = Menu.new
m.instance_eval(&block)
m
end
card = menu do
dish "Bacon", price: 8
dish "Egg", price: 3
end
card.dishesInside the block, dish "Bacon", price: 8 really calls a method of the Menu – with no receiver in front. It reads like a mini language. (instance_exec is the sibling that additionally passes arguments into the block.)
Honest warning: a DSL only pays off when many people read it often – otherwise a plain hash does the job and is easier to debug. Related building blocks: our formatter lambdas from lesson 114 were the Strategy pattern, and a null object (e.g. a GuestUser instead of nil) saves a thousand if checks.
Timelog.configure { … } runs the block via instance_eval on a fresh Configuration, Timelog.config returns it. Inside the block, project "Name", rate: 120 and round_to 15 must work.module Timelog
class Configuration
attr_reader :projects, :grid
def initialize
@projects = {}
@grid = 60
end
# def project(name, rate:)
# ...
# end
# def round_to(minutes)
# ...
# end
end
# def self.configure(&block)
# ...
# end
# def self.config
# ...
# end
end
# Timelog.configure do
# project "ProjectX", rate: 120
# round_to 15
# end