MdRecord
File-backed models for Rails. Similar to ActiveRecord but reads from markdown files with YAML frontmatter.
Installation
Add this line to your application's Gemfile:
gem "md_record"
And then execute:
bundle install
Usage
Basic Model
class Post < MdRecord::Base end
By 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::RecordNotFound
Custom Path
class Article < MdRecord::Base md_record_path "content/articles" end
Categorized Model
class Guide < MdRecord::Base include MdRecord::Categorizable md_record_categories( "getting-started" => { name: "Getting Started", position: 1 }, "advanced" => { name: "Advanced", position: 2 } ) end
Files 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"
File Format
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...
Attributes
slug- Filename without extensiontitle- From frontmatter or titleized slugdescription- From frontmattercontent- Markdown contentpublished- Booleanpublished_at- Date/Timeposition- For ordering
Methods
Class Methods
all- Load all recordspublished- Published records sorted bypublished_atdescfind(slug)- Find by slug, raisesRecordNotFoundif not found
Instance Methods
published?- Is this record published?to_param- Returns slug (for URL generation)to_html- Renders markdown to HTML
Categorizable Methods
categories- Array ofMdRecord::Categoryobjectscategory?(category)- Check if record belongs to category (accepts Category or string)category_name- Human-readable category name
RecordNotFound
MdRecord::RecordNotFound is automatically mapped to 404 in Rails (via Railtie).
Post.find("non-existent") # raises MdRecord::RecordNotFound # Rails returns 404
Components
MdRecord::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)
License
The gem is available as open source under the terms of the MIT License.