HanamiMastery

Best way to work with Front Matter in Ruby!

Episode #42

by Sebastian Wilgosz

Picture of the author

Hi there!

I have here my Hanami application, which pulls and saves my episodes from the GitHub repository for easy processing and some process automation.

By having a small GitHub integration written, I can fetch any of my episodes, and download its content for easy processing.

If you’re new to this, it’s done during my Hanami Mastery PRO series, so consider joining if you are interested in more advanced Ruby and Hanami topics.

The issue here is, that the content is returned in a raw markdown, and I would love to parse all my front_matter attributes to save in database while treating content separately for further processing.

As I’ve shown for example in episode #39, I've prepared several micro content transformations that I would love to automate and send back to the repository by making a new commit automatically.

Parsing this on my own is not a super big deal, but I’m not a fan of reinventing the wheel if somebody already did it before.

Frontmatter

If you're new to web development, the term front matter may be not obvious to you. It’s metadata that's added at the beginning of a file, often a markdown file, to provide information about the content.

Usually, it contains attributes like title, author, publication date, and tags. In Hanami Mastery episodes I leverage this to store a lot of different information about each episode, such as video identifier, episode number, and so on.

As you may see, there is a lot to extract, so let’s check what the Ruby ecosystem can bring us for this.

Meet front_matter_parser

I found the front_matter_parser gem as a very neat option to work with Front Matter in Ruby because of a few reasons.

  1. It’s simple and delivers only functionality I need.
  2. It supports multiple input sources, like markdown but also slim, haml, liquid and more.
  3. It’s written by Hanami contributor, Marc Busqué, who proved his reliability as an OSS maintainer on multiple occasions.****

With this gem, you can easily parse front matter from files and use the extracted data in your Ruby applications. Let me show you how I use it.

How to use front_matter_parser

You’ll need to install gem first or place the installation rule in the Gemfile. For this showcase, I’m going to just install it manually.

gem install front_matter_parser

Please notice, that this gem is self-contained, meaning it has no other dependencies to run. Having that done, let’s check my script.

Basic parsing

To extract front matter from a file, you'll need to create an instance of the FrontMatterParser::Parser class, choose the input format, and then pass in the contents of the file as a string.

require 'front_matter_parser'

file_contents = File.read('./sample.md')
parsed = FrontMatterParser::Parser.new(:md).call(file_contents)

parsed.front_matter['title']
parsed.front_matter['excerpt']
parsed.content

I can also use the parse_file method as a shortcut, and only pass in the file name.

parsed = FrontMatterParser::Parser.parse_file('sample.md')

The cool thing is, that based on the input file type, it automatically recognizes the proper source syntax, so for the haml example, it’ll work out of the box without any additional config required!

parsed = FrontMatterParser::Parser.parse_file('sample.haml')
parsed.front_matter['title']
parsed.front_matter['excerpt']
parsed.content

Transformations

However powerful this is, it’s not yet all. You can write your own parsers, to understand the front matter syntax for your input or you can create your own loaders.

Loaders are functions that you can use to customize how the string you read is interpreted by writing your own loaders.

The simple loader would look like this:

symbolized = ->(string) { YAML.load(string).transform_keys(&:to_sym) }

Then I can pass the loader into my parser, and suddenly all my keys get symbolized.

# For a file
FrontMatterParser::Parser.parse_file('sample.md', loader: symbolized)

You may think it’s not much, but it plays super nicely with the whole DRY and Hanami ecosystem, where we can leverage libraries like: dry-transformer, to write really complex transformations.

You may see more about complex transformations in Ruby in the Episode 6, which is one of the more popular I’ve recorded so far.

Summary

front_matter_parser is a lightweight and easy-to-use Ruby gem that makes it trivial to extract front matter from files in your Ruby projects.

With just a few lines of code, you can extract metadata from your files and use it in your applications. However, following the DRY philosophy of providing simple functionality in a very extendable way, it’s just the go-to if you want to work with markdown or any other type of front matter input.

Become an awesome subscriber!

If you want to see more content in this fashion, Subscribe to my YT channelNewsletter and follow me on Twitter!

Thanks

I want to especially thank my recent sponsors,

and [all the Hanami Mastery PRO subscribers, for supporting this project, I really appreciate it!

Consider sponsoring?

If you want to support us, check out our Github sponsors page or join Hanami Mastery PRO to gain the access to more learning resources and our private discord server!

Do you know great Ruby gems?

Add your suggestion to our discussion panel!

I'll gladly cover them in the future episodes! Thank you!

Suggest topicTweet #suggestion

May also interest you...

#39 HTML from markdown made simple!
commonmakerclitransformations

Have you ever considered how to efficiently render HTML out of your markdown input in ruby? Here we cover this problem with additional custom cosmetic improvements.

Showing flash messages in Hanami is trivial, and it is even shown in the official guides. In this episode though, we make this future-proof, testable, and maintainable for a future growth of your application.

Probably any web app nowadays requires font icons to be loaded this or other way. In this episode, I'm showing the integration of Font Awesome icons in Hanami 2 applications.

This episode is a special release, when Seb interviews Tim Riley and Luca Guidi from the Hanami Core Team, asking them questions collected from the community! This way we enjoy reaching our important milestone of releasing 50th Hanami Mastery episode!

Coffee buy button
Trusted & Supported by
DNSimple

1 / 2
Open Hanami Jobs

We use cookies to improve your experience on our site. To find out more, read our privacy policy.