Redcarpet 的 render 實作改變 ( 1.0 -> 2.0 )
這幾天在改 ruby-taiwan 的 code,我跟 @chitsaou 有被這個問題整到。
Redcarpet 之前在 1.0 的實作方式是 new 出一個 instance 再 .to_html 轉成 markdown 物件。
require 'redcarpet'
markdown = Redcarpet.new("Hello World!")
puts markdown.to_html
在 2.0 換成這種的寫法。先定義 renderer 再轉。是完全不相容的
html_renderer = Redcarpet::Render::HTML.new({
:autolink => true,
:fenced_code_blocks => true,
:tables => true,
:strikethrough => true,
:lax_htmlblock => true,
:no_intraemphasis => true
})
markdown = Redcarpet::Markdown.new(html_renderer)
data = markdown.render(data)
本來寫寫小東西是沒差的...
不過今天還在寫其他 feature:也就是想把 Gollum 接到 這個專案作為 Git 的 backend 。結果遇到幾個問題...
1. Gollum 1.3.1 ( stable ) 不支援 GFM..
2. Gollum 現在 trunk 上有人寫的 for GFM 的 patch,雖然可以跑 redcarpet,而 markup_class 怎麼試都不對。因為 Gollum 的 redcarpet 沒鎖版本,lock 到哪個看運氣,但兩個實作介面根本不一樣。
最後害我只好開大決招,在 class 裡面偵測版本,然後兩種版本都塞。
寫了這樣的髒 code,然後拉 pull request 回去。
if Gem::Version.new(Redcarpet::VERSION) > Gem::Version.new("1.17.2")
html_renderer = Redcarpet::Render::HTML.new({
:autolink => true,
:fenced_code_blocks => true,
:tables => true,
:strikethrough => true,
:lax_htmlblock => true,
:no_intraemphasis => true
})
markdown = Redcarpet::Markdown.new(html_renderer)
data = markdown.render(data)
else
flags = [
:autolink,
:fenced_code,
:tables,
:strikethrough,
:lax_htmlblock,
:no_intraemphasis
]
data = Redcarpet.new(data, *flags).to_html
end
不過意外學到一招 Gem::Version.new
,不用自己寫 parser 比 gem 版本...
那個,別忘了開 :filter_html
XD
原先的 code 裡面沒開...
←明顯忘了
是 Gollum 沒有開 XD
它有個範例是可以 render 出 Man Page 的,也就是說,輸出的資料不再限制於 HTML 了。我想以後有人會做出 LaTeX 的 renderer ... XDD
XDDDDDDDD
今天 Redcarpet 2.0.0 正式版出來了。為了妥協 1.x 的 API ,新增了一個 compat.rb
,只要 require 'redcarpet/compat'
,就可以繼續使用 Markdown.new(text).to_html
這種方式...
不過妥協畢竟是妥協,這種方式(理所當然)不能夠增加任何 extension ...XD
真是太可惡了 XDDDD
往好處想,用這種方式就不能加上 syntax highlighting ,所以還是得鐵了心放棄舊版 API ...XD
真的好心機啊!