Use the Markdown method in Ruby on Rails, railsmarkdown

Source: Internet
Author: User
Tags ruby on rails

Use the Markdown method in Ruby on Rails, railsmarkdown

The Redcarpet and pygments. rb are used to implement Markdown syntax and code syntax highlighting respectively:

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/Gemfile:

gem 'redcarpet'gem 'pygments.rb'

It must be noted that pygments. rb depends on Python, so ensure that Python 2.xis installed on the machine.

Then add the corresponding redcarpet and pygments. rb code to/app/controllers/comments_controller.rb:

class ApplicationController < ActionController::Base # Prevent CSRF attacks by raising an exception. # For APIs, you 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 end protected # Markdown with Redcarpet def markdown(text)  renderer = HTMLwithPygments.new({   :filter_html => true,   :hard_wrap => true,   :link_attributes => {:rel => 'external nofollow'}  })  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 endend

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

<%= markdown @post.content %>

Syntax rules are similar to Markdown on Github, which greatly improves the efficiency of code words.

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.