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.