Integrate Markdown in Rails Apps with ActiveRecord
Introduction: Integrating Markdown with Ruby on Rails and ActiveRecord
In this tutorial we’re going to demonstrate how you can integrate Markdown in your Ruby on Rails application, especially when the context involves ActiveRecord models.
Markdown is a lightweight markup language with plain-text-formatting syntax, and Ruby on Rails, a powerful web application framework for the Ruby programming language. ActiveRecord, an essential part of Ruby on Rails, is the M in MVC (model-view-controller), which is responsible for data handling.
Consider this scenario: Your Rails application includes a blog functionality and you want to provide your users with an interface to write their blog posts in Markdown. For this, you save this Markdown text in your database using ActiveRecord, and then render it as converted HTML in the view.
Dependencies
To effectively handle Markdown in Rails, we are going to make use of the Redcarpet gem. It’s a Ruby library for Markdown processing that smells like butterflies and popcorn.
Include Redcarpet in your Gemfile:
gem 'redcarpet'
After this, run the bundle command:
$ bundle install
Using ActiveRecord for storing Markdown text
Consider a Blog model with a content
field where the Markdown text will be stored.
class Blog < ApplicationRecord
end
We store the Markdown formatted text in the content
column of our blogs table.
Rendering Markdown content to HTML
To render the blog posts in HTML after being saved as Markdown, we’ll use Redcarpet. Let’s create a helper that can be reused to parse any markdown content.
module ApplicationHelper
def render_markdown(text)
renderer = Redcarpet::Render::HTML.new
markdown = Redcarpet::Markdown.new(renderer)
markdown.render(text).html_safe
end
end
We’ve kept the output as .html_safe
to return safe HTML back to the view without escaping it.
In our views, we can now make use of this helper method to render markdown:
<%= render_markdown(@blog.content) %>
Preview Markdown content
Let’s take it a step further and integrate a live preview for our Markdown editor. Here is a detailed guide on how to preview markdown.
Conclusion
And that’s a wrap! Your Ruby on Rails application is now integrated with Markdown using ActiveRecord with HTML rendering ability. Harnessing the power of ActiveRecord with Markdown paves way for a lightweight and easy-to-style option.