back

Ruby DSL - Part 3: summary

The takeaway from part 1 and part 2 is that it’s easy to make a more readable dsl by using a bit of meta programming.

Machinist does this using instance_eval and method_missing. Without those methods, the machinist interface might look something like this:

1
2
3
4
blueprint = Blueprint.new(Person)
blueprint.has_attribute("name", "Example name")
blueprint.has_attribute("birthday", Time.now)
blueprint.has_attribute("hair_color", "brown")

rather than this

1
2
3
4
5
Person.blueprint do 
  name {"Example name"}
  birthday {Time.now}
  hair_color {"Brown"}
end

Machinist adds methods to ActiveRecord models to let us say Person.blueprint instead of Blueprint.new(Person).

Machinist also uses instance_eval to take a block, so that we can say Person.blueprint do; end; rather than having to say person.has_attribute over and over.

Finally, it uses method_missing to let us say name {"Example name"} instead of blueprint.has_attribute(“name”, “example name”)

February 25, 2009