File-backed models for Rails. Similar to ActiveRecord but reads from markdown files with YAML frontmatter.
Add this line to your application's Gemfile:
gem "md_record"And then execute:
bundle installclass Post < MdRecord::Base
endBy default, files are loaded from app/views/posts/ (based on model name).
Post.all # All posts
Post.published # Only published posts
Post.find(slug) # Find by slug or raise MdRecord::RecordNotFoundclass Article < MdRecord::Base
md_record_path "content/articles"
endclass Guide < MdRecord::Base
include MdRecord::Categorizable
md_record_categories(
"getting-started" => { name: "Getting Started", position: 1 },
"advanced" => { name: "Advanced", position: 2 }
)
endFiles are organized in subfolders:
app/views/guides/
getting-started/
first-steps.md
advanced/
custom-config.md
Guide.categories # Returns array of MdRecord::Category objects
guide.category?("getting-started") # Check if guide belongs to category
guide.category_name # "Getting Started"Markdown files with YAML frontmatter:
---
title: My Post Title
description: A short description
published: true
published_at: 2024-01-15
position: 1
---
# Content here
Your markdown content...slug- Filename without extensiontitle- From frontmatter or titleized slugdescription- From frontmattercontent- Markdown contentpublished- Booleanpublished_at- Date/Timeposition- For ordering
all- Load all recordspublished- Published records sorted bypublished_atdescfind(slug)- Find by slug, raisesRecordNotFoundif not found
published?- Is this record published?to_param- Returns slug (for URL generation)to_html- Renders markdown to HTML
categories- Array ofMdRecord::Categoryobjectscategory?(category)- Check if record belongs to category (accepts Category or string)category_name- Human-readable category name
MdRecord::RecordNotFound is automatically mapped to 404 in Rails (via Railtie).
Post.find("non-existent") # raises MdRecord::RecordNotFound
# Rails returns 404MdRecord::Base- Base class for modelsMdRecord::Categorizable- Concern for categorized modelsMdRecord::Category- Value object for categoriesMdRecord::Loader- Loads files from a directoryMdRecord::CategorizedLoader- Loads files from category subdirectoriesMdRecord::FrontmatterParser- Parses YAML frontmatterMdRecord::MarkdownRenderer- Custom Redcarpet renderer with asset path supportMdRecord::RecordNotFound- Exception for missing recordsMdRecord::Railtie- Rails integration (auto-loaded)
The gem is available as open source under the terms of the MIT License.