If Node is an ActiveRecord class that implements acts_as_tree, then fixtures would usually look like:
root:
id: 1
parent_id:
name: Root Node
child_1:
id: 2
parent_id: 1
name: First Child
child_1_1:
id: 3
parent_id: 2
name: Sub Child 1
child_1_2:
id: 4
parent_id: 2
name: Sub Child 2
child_2:
id: 5
parent_id: 1
name: Second Child
This gets really hard to read, and to manage with all the juggling of those ID's. Plus it's difficult, at a glace, to get a good idea of the data's structure. With Doozer, you can get a much better visualization of this kind of fixture data, and not have to manage as much tedium:
Doozer.define :node do
field_order :name
block_affects :child=>:parent_id
end
node "Root Node" do
node "First Child" do
node "Sub Child 1"
node "Sub Child 2"
end
node "Second Child"
end
This Doozer script generates the following YAML:
node_1:
id: 1
parent_id:
name: Root Node
node_2:
id: 2
parent_id: 1
name: First Child
node_3:
id: 3
parent_id: 2
name: Sub Child 1
node_4:
id: 4
parent_id: 2
name: Sub Child 2
node_5:
id: 5
parent_id: 1
name: Second Child
You'll notice that the names are now generated; node_1 instead of root. We can specify fixture names too. If the first argument to the node() macro (that Doozer.define(sym) generates) is a Symbol, then it's used as the fixture's name. So, our updated Doozer fixture looks like this:
node :root, "Root Node" do
node :child_1, "First Child" do
node :child_1_1, "Sub Child 1"
node :child_1_2, "Sub Child 2"
end
node :child_2, "Second Child"
end
Now the generated fixture will be the same as our original listing.
You can reference a named fixture multiple times in the same Doozer script. Each time it will collect the information sent and merge it with previous calls. So, for example, let's say we just want to show the node structure first, and then fill out the node names in a more tabular fashion. Our Doozer fixture changes to this:
node :root do
node :child_1 do
node :child_1_1
node :child_1_2
end
node :child_2
end
node :root, "Root Node"
node :child_1, "First Child"
node :child_1_1, "Sub Child 1"
node :child_1_2, "Sub Child 2"
node :child_2, "Second Child"
This generates the same fixture as before, only now the structure really shows through.
Now let's say I've added a created_on field to the Node class. I don't really wanna go through every node in the fixture and add that info, I'd rather specify a default value for it. Doozer makes this quite easy, you just add the defaults to the definition block, like so:
Doozer.define :node do
field_order :name
block_affects :child=>:parent_id
defaults :created_on=>Time.now.to_s(:db)
end
And now, all of your generated fixtures will have created_on fields with the value returned from Time.now.to_s(:db).