在Ruby on Rails中使用Markdown的方法_ruby專題

來源:互聯網
上載者:User

實現 Markdown 文法和代碼文法高亮分別是用的 Redcarpet 和 pygments.rb 兩個 Gem:

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

在/Gemfile中添加如下兩行:

gem 'redcarpet'gem 'pygments.rb'

需要說明的是,pygments.rb 依賴於 Python,所以確保機器已經安裝了 Python 2.x。

然後在/app/controllers/comments_controller.rb中添加相應 redcarpet 和 pygments.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

最後在 View 中就可以直接調用 markdown 方法來處理部落格本文了:

<%= markdown @post.content %>

文法規則類似 Github 上的 Markdown,碼字效率大大提高。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.