views:

292

answers:

1

I have a system that filters template files through erb. Using convention over configuration, the output files get created in a file hierarchy that mirrors the input files. Many of the files have the same names, and I was able to use the directories to differentiate them.

That plan worked until I needed to associate additional info with each file. So I created a YAML file in each directory with the metadata. Now I have both convention and configuration. Yuck.

Then I learned Webby, and the way it includes a YAML metadata section at the top of each template file. They look like this:

---
title: Baxter the Dog
filter: textile
---
All the best little blogs use Webby.

If I could implement a header like that, I could ditch my hierarchy and the separate YAML files. The Webby implementation is very generic, implementing a new MetaFile class that separates the header from the "real text", but it seems more complicated than I need.

Putting the metadata in an erb comment seems good -- it will be automatically ignored by erb, but I'm not sure how to access the comment data.

<%#
title: Baxter the Dog
%>

Is there a way to access the erb comments? Or maybe a different approach? A lot of my templates do a bunch of erb stuff, but I could run erb in a separate step if it makes the rest easier.

+1  A: 

How about if you dump your content as YAML too. Presumably the metadata is simply a Hash dumped to YAML. You could just append the content as string in a second YAML document in the same file :-

---
title: Baxter the Dog
filter: textile
--- |
Content line 1
Content line 2
Content line 3

Dumping is as simple as :-

File.open('file.txt', 'w') do |output|
  YAML.dump(metadata, output)
  YAML.dump(content, output)
end

Loading is as simple as :-

File.open('file.txt') do |input|
  stream = YAML.load_stream(input)
  metadata, content = stream.documents
end

Note that the pipe character appears in the YAML so that newlines in the content string are preserved.

floehopper
I like this approach; nicer for human viewing than the erb comment. Some of my content might already include yaml, but I think I'm safe if I escape any document separators? \---
slothbear