Andrew
Andrew

Reputation: 238917

How to use YAML front and back matter in Ruby?

I have heard of the term "front matter" and "back matter" to refer to some YAML parsing at the beginning or end of a non-YAML file. However, I can't seem to find any examples/documentation of how to implement this. Maybe this isn't a standard YAML feature. How can I make use of this feature in my Ruby project?

FYI: The reason I want to do this is to be able to require some ruby files at the top, and assume the rest is YAML. I don't think this is normally allowed in a YAML file.

Upvotes: 0

Views: 329

Answers (1)

Andrew
Andrew

Reputation: 238917

I just came across a nice example of something similar to what I am trying to do. It isn't necessarily an example of "front/back matter" but it might help someone in the future:

Using the __END__ keyword, you can stop ruby from parsing the rest of the file. The rest of the file is stored in a DATA variable, which is actually a File object:

#!/usr/bin/env ruby
%w(yaml pp).each { |dep| require dep }

obj = YAML::load(DATA)

pp obj

__END__
---
-
  name: Adam
  age: 28
  admin: true
-
  name: Maggie
  age: 28
  admin: false

Source

Upvotes: 2

Related Questions