在Ruby on Rails中使用Markdown的方法
實(shí)現(xiàn) Markdown 語(yǔ)法和代碼語(yǔ)法高亮分別是用的 Redcarpet 和 pygments.rb 兩個(gè) 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'
需要說(shuō)明的是,pygments.rb 依賴于 Python,所以確保機(jī)器已經(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 方法來(lái)處理博客正文了:
<%= markdown @post.content %>
語(yǔ)法規(guī)則類似 Github 上的 Markdown,碼字效率大大提高。
- python 自動(dòng)化將markdown文件轉(zhuǎn)成html文件的方法
- 獻(xiàn)給寫作者的 Markdown 新手指南
- 可能是最通俗的一篇介紹markdown的文章
- 玩轉(zhuǎn)markdown 分享幾個(gè)需要用到的工具
- Markdown+Bootstrap圖片自適應(yīng)屬性詳解
- Markdown與Bootstrap相結(jié)合實(shí)現(xiàn)圖片自適應(yīng)屬性
- 使用Python來(lái)開(kāi)發(fā)Markdown腳本擴(kuò)展的實(shí)例分享
- 如何使用Gitblog和Markdown建自己的博客
- Markdown語(yǔ)法備忘
- markdown簡(jiǎn)介和語(yǔ)法介紹
- js驗(yàn)證手機(jī)號(hào)碼
相關(guān)文章
Ruby中的反射(Reflection)應(yīng)用實(shí)例
這篇文章主要介紹了Ruby中的反射(Reflection)應(yīng)用實(shí)例,實(shí)現(xiàn)通過(guò)一個(gè)類名字符串構(gòu)造一個(gè)類對(duì)象和訪問(wèn)成員變量和私有方法 ,需要的朋友可以參考下2014-06-06
使用Ruby程序?qū)崿F(xiàn)web信息抓取的教程
這篇文章主要介紹了使用Ruby程序?qū)崿F(xiàn)web信息抓取的教程,本文來(lái)自于IBM官方網(wǎng)站技術(shù)文檔,需要的朋友可以參考下2015-04-04
詳解組合模式的結(jié)構(gòu)及其在Ruby設(shè)計(jì)模式編程中的運(yùn)用
這篇文章主要介紹了組合模式的結(jié)構(gòu)及其在Ruby設(shè)計(jì)模式編程中的運(yùn)用,組合模式在Ruby on Rails框架開(kāi)發(fā)項(xiàng)目中也經(jīng)常被用到,需要的朋友可以參考下2016-03-03
ruby實(shí)現(xiàn)的一個(gè)異步文件下載HttpServer實(shí)例
這篇文章主要介紹了ruby實(shí)現(xiàn)的一個(gè)異步文件下載HttpServer,使用eventmachine和em-http-server實(shí)現(xiàn),需要的朋友可以參考下2014-07-07

