Marksmith

Episode #512 by Teacher's Avatar David Kimura

Summary

Easily add Markdown support to your Rails applications with Marksmith. This isn't a drop-in replacement to ActionText, but can be used with text or blob columns. Marksmith integrates easily with ActiveStorage for handling file uploads. In this episode, we'll explore setting up Marksmith and some best practices.
rails view wysiwyg 7:48

Chapters

  • Introduction (0:00)
  • Creating the scaffold (1:35)
  • Installing Marksmith (1:55)
  • Adding Marksmith (2:36)
  • Using Marksmith (3:13)
  • Demo (3:49)
  • Understanding the rendering (4:17)
  • Sanitizing the displayed content (4:47)
  • Final Thoughts (6:29)

Resources

Download Source Code

Summary

# Terminal
rails g scaffold products name description:text
rails active_storage:install
bundle add marksmith commonmarker

# For esbuild
yarn add @avo-hq/marksmith

# For importmaps
bin/importmap pin @avo-hq/marksmith

# app/javascript/controllers/index.js
import { MarksmithController } from "@avo-hq/marksmith"
application.register("marksmith", MarksmithController)

// NOTE: For esbuild applications, do not edit the index.js directly. Instead, put it in the application.js or elsewhere.

# app/views/layouts/application.html.erb
<%= stylesheet_link_tag :marksmith, "data-turbo-track": "reload" %>

# app/views/products/_form.html.erb
<%= marksmith_tag %>
<div class="my-5">
  <%= form.label :description %>
  <%= form.marksmith :description, rows: 4, class: ["block shadow-sm rounded-md border px-3 py-2 mt-2 w-full", {"border-gray-400 focus:outline-blue-600": product.errors[:description].none?, "border-red-400 focus:outline-red-600": product.errors[:description].any?}] %>
</div>

# app/views/products/_product.html.erb
<div class="ms:prose ms:prose-slate">
  <%= sanitize(
    marksmithed(product.description),
    attributes: %w(style src class lang),
    tags: %w(table th tr td span) +
    ActionView::Helpers::SanitizeHelper.sanitizer_vendor.safe_list_sanitizer.allowed_tags.to_a) %>
</div>