4

I was reading through Redcarpet's documentation and came across this sentence:

The Markdown object is encouraged to be instantiated once with the required settings, and reused between parses.

What is the best way to go about doing this in a Rails app?

I watched Ryan Bates' railscast on Redcarpet and he has a helper method in application_helper.rb where every method call instantiates a new Redcarpet object, like so:

def markdown(text)
  options = [:hard_wrap, :filter_html, :autolink, :no_intraemphasis, :fenced_code, :gh_blockcode]
  Redcarpet.new(text, *options).to_html.html_safe
end

Is this not the best way to go about doing this? Thanks for any advice.

paradox460
  • 174
  • 1
  • 11
Kurt Mueller
  • 3,173
  • 2
  • 29
  • 50

1 Answers1

1

Not sure if this is the rails way of doing things, but it seems fine, and doesn't violate POLA or the like, so hopefully it will suit your needs.

Create a markdown.rb file in your config/initializers/ folder, and use some variation of the following code snippet:

class MultiRenderer < Redcarpet::Render::HTML
  include Redcarpet::Render::SmartyPants
end

module Paradox
  Markdown = Redcarpet::Markdown.new(MultiRenderer)
end

Replace Paradox with the name of your application. You can add various options to the renderer or the instance of markdown, as described in the readme. The renderer I created (the MultiRenderer) has built in smartypants, so you can round quotes and whatnot

To use Markdown, simply call YourApp::Markdown.render(text), and you'll get html back. You probably need to run html_safe on that.

paradox460
  • 174
  • 1
  • 11
  • 3
    Is this global renderer thread safe? Very important when using multi-threaded environments like Puma or Sidekiq. – mpoisot Sep 27 '13 at 16:22
  • can anyone please confirm if it is thread safe to use redcarpet object between multiple threads. eg: with thin or puma?? – Arun Satyarth Feb 08 '16 at 18:10
  • I tested it with a simple script, using concurrent-ruby and latches, and it does appear to be threadsafe, since rendering markdown doesn't affect the markdown renderer (you can test that by freezing your markdown object) – paradox460 Feb 10 '16 at 22:58