DEV Community

Cover image for Parse a YML/YAML file in a Ruby on Rails app
Yaroslav Shmarov
Yaroslav Shmarov

Posted on • Originally published at blog.corsego.com on

1

Parse a YML/YAML file in a Ruby on Rails app

Instead of storing static data a database, you can create a structured YML or JSON file and parse it from your Ruby/Rails app.

I really like the data structure of a .yml file, because it is much cleaner to write than .json.

Here’s an example list of schools in the YAML format:

# db/view_data/schools.yml
- name: Austin High School
  team_name: Austin Mustangs
  city: Houston
  state: TX
  primary_color: green
  secondary_color: white

- name: Bellaire High School
  team_name: Bellaire Cardinals
  city: Houston
  state: TX
  primary_color: red-lighter
  secondary_color: white

- name: Carnegie Vanguard High School
  team_name: Carnegie Vanguard Rhinos
  city: Houston
  state: TX
  primary_color: blue
  secondary_color: red-lighter
Enter fullscreen mode Exit fullscreen mode

You can parse this data (convert it into a Hash or Array) using Ruby on Rails native yaml parsers!

  1. Parse a local YAML file with pure Ruby :
require 'yaml'
path = "/Users/yaroslavshmarov/Documents/GitHub.nosync/schools.yml"
@schools = YAML::load File.open(path)

@schools.first.fetch('name')
# => "Austin High School"
Enter fullscreen mode Exit fullscreen mode

Source: Ruby YAML docs

  1. Parse a YAML file inside a Rails app:
# a controller action
  # @schools = YAML::load File.open("#{Rails.root.to_s}/db/fixtures/schools.yml") # ruby way
  @schools = YAML.load_file('db/fixtures/schools.yml') # rails way
  @schools.inspect
Enter fullscreen mode Exit fullscreen mode

Render the results in a view:

# a view
<% @schools.each do |school| %>
  <%= school.fetch('name') %>
  <%= school['name'] %>
<% end %>
Enter fullscreen mode Exit fullscreen mode

Source: Rails YAML.load_file docs

That’s it! 🤠

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more