在Ruby on Rails中使用Markdown的方法
實現(xiàn) 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,所以確保機器已經(jīng)安裝了 Python 2.x。
然后在/app/controllers/comments_controller.rb中添加相應(yīng) 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 end end
最后在 View 中就可以直接調(diào)用 markdown 方法來處理博客正文了:
<%= markdown @post.content %>
語法規(guī)則類似 Github 上的 Markdown,碼字效率大大提高。
相關(guān)文章
Ruby實現(xiàn)命令行中查看函數(shù)源碼的方法
這篇文章主要介紹了Ruby實現(xiàn)命令行中查看函數(shù)源碼的方法,,需要的朋友可以參考下2014-07-07win10下使用virtualbox + vagrant配置ruby開發(fā)機環(huán)境
Vagrant是一個基于Ruby的工具,用于創(chuàng)建和部署虛擬化開發(fā)環(huán)境。它 使用Oracle的開源VirtualBox虛擬化系統(tǒng),使用 Chef創(chuàng)建自動化虛擬環(huán)境。搭配Cmder如絲般順滑,實現(xiàn)你所有關(guān)于Mac&Linux的幻想2017-08-08