Ways to use markdown in Ruby on Rails _ruby topics

Source: Internet
Author: User
Tags ruby on rails

Implementing Markdown syntax and code syntax highlighting is the use of the Redcarpet and pygments.rb two gems:

Https://github.com/vmg/redcarpet
Https://github.com/tmm1/pygments.rb
Https://github.com/richleland/pygments-css
http://pygments.org/docs/lexers/

Add the following two lines to the/gemfile:

Gem ' Redcarpet '
gem ' pygments.rb '

It should be explained that PYGMENTS.RB relies on python, so make sure the machine has Python 2.x installed.

Then add the corresponding Redcarpet and PYGMENTS.RB code in the/APP/CONTROLLERS/COMMENTS_CONTROLLER.RB:

Class Applicationcontroller < Actioncontroller::base # prevent CSRF attacks by raising a exception.
 # for APIs, your may want to use:null_session instead.  Protect_from_forgery with:: Exception Helper_method [: Markdown] # Highlight code with pygments class Htmlwithpygments
   < redcarpet::render::html def block_code (code, language) language = "text" If Language.blank? SHA = digest::sha1.hexdigest (code) Rails.cache.fetch ["Code", Language, Sha].join ("-") do Pygments.highlight (code, : lexer => language) End-end-protected # markdown with Redcarpet def markdown (text) renderer = Htmlwith Pygments.new ({: Filter_html => true,: Hard_wrap => true,: Link_attributes => {: rel => ' external nofol
   Low '}} ' options = {: Autolink => true,: No_intra_emphasis => true,: Fenced_code_blocks => True, : Lax_html_blocks => True,: Strikethrough => true,: Superscript => true,: Tables => true} REDCArpet::markdown.new (renderer, Options). Render (text). Html_safe End

 

Finally, you can call the Markdown method directly in View to process the blog body:

<%= markdown @post. Content%>

The grammar rules resemble the markdown on the Github, and the code word efficiency is greatly improved.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.