Use Markdown and Pygments
Markdown is pretty awesome for writing, you just type in some tag and your article is formated. You just need to concentrate on the content of your article without worrying about format.
In your rails app, you can use easily do this. Here is a quick guide on how to use markdown and pygments in your rails app.
Add Gem
First thing you need to do is to add redcarpet and pygments.rb gems to you Gemfile. Just add gem 'gem 'redcarpet', '~> 3.3'
and gem 'pygments.rb', '~> 0.6.3'
to your Gemfile and run bundle install
and restart your server.
Add helper
A helper need to be created to handle this markdown stuff. In you application_helper.rb
, add this markdown method.
def markdown(content)
renderer = Redcarpet::Render::HTML.new(hard_wrap: true, filter_html: true)
options = {
autolink: true,
no_intra_emphasis: true,
disable_indented_code_blocks: true,
fenced_code_blocks: true,
lax_html_blocks: true,
strikethrough: true,
superscript: true
}
Redcarpet::Markdown.new(renderer, options).render(content).html_safe
end
And then instead of using @post.content
, try markdown(@post.content)
and your article written in markdown syntax will be rendered to html elements. Simple enough? Yes, that’s it!
Syntax Highlighting
Wait, one more thing. The code is not highlighted, which is not cool. Remember pygments.rb? Yes, we already installed that gem. We need some CSS to style the code. Here is a github like syntax highlighting, it’s pretty awesome, go to checkout! Create a file _pygments.css.scss
and add the css here, and then @import 'pygments'
in your application.css.scss.
Also, you need to change your helper a bit.
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, lexer: language)
end
end
Then change Redcarpet::Render::HTML
to HTMLwithPygments
in your markdown method. Finally, your code should looks something like this:
module ApplicationHelper
class HTMLwithPygments < Redcarpet::Render::HTML
def block_code(code, language)
Pygments.highlight(code, lexer: language)
end
end
def markdown(content)
renderer = HTMLwithPygments.new(hard_wrap: true, filter_html: true)
options = {
autolink: true,
no_intra_emphasis: true,
disable_indented_code_blocks: true,
fenced_code_blocks: true,
lax_html_blocks: true,
strikethrough: true,
superscript: true
}
Redcarpet::Markdown.new(renderer, options).render(content).html_safe
end
end