Markdown and code syntax highlighting in Ruby on Rails (using RedCarpet and CodeRay)
Markdown is a popular text-to-HTML conversion tool. In order to use Markdown with code syntax highlighting, use RedCarpet and CodeRay gems. Ryan Bates made a Railscast episode (#272) on RedCarpet, but it is somewhat outdated now. The episode has more dependencies and uses a deprecated Albino gem.
Place the following in the Rails app.
Gemfile
gem 'redcarpet', '~> 2.1.1'
gem 'coderay', '~> 1.0.7'
application_helper.rb
class CodeRayify < Redcarpet::Render::HTML
def block_code(code, language)
CodeRay.scan(code, language).div
end
end
def markdown(text)
coderayified = CodeRayify.new(:filter_html => true,
:hard_wrap => true)
options = {
:fenced_code_blocks => true,
:no_intra_emphasis => true,
:autolink => true,
:strikethrough => true,
:lax_html_blocks => true,
:superscript => true
}
markdown_to_html = Redcarpet::Markdown.new(coderayified, options)
markdown_to_html.render(text).html_safe
end
whatever_view_file.html.erb
<%= markdown(@submission.content) %>
The result is this gorgeous looking syntax highlighting.

To indicate language you are using the code should be wrapped around the following.
``` ruby
some_code_here
```
Also make sure that you do bundle install and restart your server.
Alternatively, if you’d like to line number on your code, you can change this line …
CodeRay.scan(code, language).div
to the following.
CodeRay.scan(code, language).div(:line_numbers => :table)
-
jfong23 likes this
-
stevekinney likes this
-
mehulkar likes this
-
allfuzzy posted this