Redcarpet Markdown gem: instantiating the Markdown object only once & reusing it between parses

StackOverflow https://stackoverflow.com/questions/18240339

Pregunta

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.

¿Fue útil?

Solución

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.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top