January 16, 2023

Using YAML with Ruby on Rails

I find YAML to be a godsend when rendering static data that doesn't necessarily need to be a part of a database using Ruby on Rails.

In the Ruby ecosystem, YAML is the de facto standard for setting and sourcing configurations or various settings that more or less remain constant.

The Ruby on Rails framework uses YAML heavily for localization, configuration, and more, but you can tap into YAML files in your applications.

For my course Hello Rails I used YAML to render almost all content on the marketing page you see when you visit the site. It didn't make much sense to host that data in a database, and it was way quicker to update and fine-tune over time.

Example application

For this guide, I made a very basic Rails 7 app.

rails new yaml_demo -c tailwind -j esbuild

After the application was bootstrapped, I generated a simple static_controller.rb file, which would serve static pages (i.e., pages that don't make database queries to render data).

rails generate controller static faq

When generating a controller, you can pass the additional methods/actions (i.e., pages in our case) you want to create. I wanted one called faq in the end.

Finally, in the routes.rb file, I quickly changed the root path that comes commented out by default. Notice I removed the dynamically generated get routing line that came with the controller generator command I ran before.

# config/routes.rb
Rails.application.routes.draw do
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  root "static#faq"

Parsing YAML with Ruby

Ruby has built-in support for YAML, but you must call certain classes and methods to parse a .yml file type correctly.

I like to define a universal method for parsing YAML in my Rails applications. This often lives inside my application_controller.rb file so subsequent controllers can inherit the method, and we can practice the D.R.Y. (Don't repeat yourself) principle.

Ruby, by default, can parse YAML if you pass it a path to a .yml file. The method looks like the following:

def parse_yaml(file)

The YAML class of Ruby calls a load method which expects a relative source file that Ruby can open using the File.open method.

I added the method to my application_controller.rb file.

# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
  def parse_yaml(file)

Now we have a tool for use inside our other controllers.

Rendering YAML content

Now that we have a StaticController Rails controller class in our app and a faq method defined, we can process a .yml file in a view.

The .yml file we source needs to have some data so to make things quicker; I added the questions and answers from my course Hello Rails as an example.

The questions and answers live in a folder called static_data (feel free to name this whatever you like)at the root of my Ruby on Rails project.

Inside the static_data folder, added a file called faqs.yml. Inside the file is the following:

- question: What version of Ruby on Rails is this for?
  answer: This course is written with Rails 7.0.3 using Ruby 3.0.3. I'll update the source code and book periodically as Rails and Ruby update. Screencasts will be updated for significant breaking changes in Rails where necessary.
- question: I lost, deleted, or never got my welcome email. What do I do now?
  answer: Reconfirm your [account](https://hellorails.io/auth/verification/new) or [email me](https://hellorails.io/contact/new) with the email you used to buy the course and I'll hook you up.
- question: What format are the videos? How do I watch them? Can I download them as well?
  answer: After buying the course you will be emailed access to a personalized dashboard for your chosen version of the Hello Rails course. There you can watch the videos and download any materials. Each video is stream-able and downloadable.
- question: Will this course make me a pro Ruby on Rails developer?
  answer: Not even the slightest, but as with anything, practice makes perfect. My intent is to guide you through building an app from start to finish and explain the "how" and "why" along the way. In doing so, you should be able to take the knowledge gained and construct your own applications. Ultimately, to get better, always be building 🙌.
- question: What if this course isn't what I was hoping?
  answer: That happens and I get it. I want you to be satisfied. If you didn't learn from the course or assumed it was something else, email me or contact me [here](https://hellorails.io/contact/new) within 30 days to get a refund.
- question: Do you offer student discounts?
  answer: Absolutely. I was once a student and understand everything gets pricey so I'm happy to help. [Contact me](https://hellorails.io/contact/new) with some current proof that you're an active student before purchasing the course and I'll hook you up.
- question: Why should I buy this when other tutorials are free (ahem..RailsTutorial)?
  answer: There are no doubt a lot of sweet tutorials out there. My approach with Hello Rails is to be very thorough by explaining core concepts and their reasoning. Ultimately, my goal is to provide realistic use cases makers/developers deal with day-to-day. This course is more modern on the design and development front and also touches on things like billing, user roles/permissions, and integrating other frameworks/gems. The Starter course gives you the basic knowledge of the Ruby on Rails by building a Reddit clone from start to finish. The Master course goes one step further addressing things like payments, search, user roles/permissions, and much more.
- question: I have another question!
  answer: Sure thing, [Contact me](https://hellorails.io/contact/new) directly from this site or email me.

Setting up the controller

With our data added, we can build an instance of our frequently asked questions in the StaticController.

class StaticController < ApplicationController
  def faq
    @faqs = parse_yaml("#{Rails.root.to_s}/static_data/faqs.yml")

Here I'm setting up an instance variable called @faqs and assigning it to our parse_yaml method. The parse_yaml method passes the relative path of the faqs.yml file we just added using some handy built-ins from Rails.

Calling Rails.root returns a pathname to the current directory of your Rails application. Since we need to build a dynamic path, we'll need to append the to_s method to return a string version of the path. Using interpolation, we can stitch the returned string to additional path details.

Outputting the data to a view

Inside our app/views/static folder, there should be a faq.html.erb file. This single static page is meant to be more informational than part of the application.

We can style the page, add some elements and return the FAQ data using erb. I used some minimal Tailwind CSS styles to format the data, but the sky is the limit for how this could look.

<!-- app/views/static/faq.html.erb-->
<div class="max-w-3xl mx-auto">
  <h1 class="font-bold text-3xl mb-6">FAQs</h1>
  <% @faqs.each do |faq| %>
    <details class="p-3 rounded border mb-6">
      <summary class="font-semibold"><%= faq['question'] %></summary>
      <div><%= faq['answer'] %></div>
  <% end %>


I've only tapped the surface of the power of using YAML to expand ideas and concepts around your Ruby on Rails applications. You could go another step further and build your configuration for some third-party Ruby gem as another example.

With the new knowledge of how to parse YAML with Ruby and Rails, I hope some ideas have sparked for you!

Tags: yaml

Leave a reply

Sign in or Sign up to leave a response.

1 response

Isabelle Ward
Icons/link diagonal

Dewabet adalah Web agen lapak303 online yang udah berdiri lebih berasal dari 8 tahunan bersama dengan sejalan saat Dewabet sudah terkenal sebagai agen formal terpercaya bersama dibuktikan semakin banyaknya member dewa bet yang mendaftar dan login bermain Poker, Dominoqq, Togel, Sportsbook, Live Casino dan juga beraneka game lainnya layaknya e-games slot online dan dingdong.

Est. reading time: 7 minutes
Stats: 201 views



Part of the Ruby on Rails collection