almost 4 years ago

系統:

Mac OS X Yosemite 10.10.1
Ruby 2.2.0
Rails 4.2.0

相關連結

pygments ( http://pygments.org/ )
pygments.rb ( https://github.com/tmm1/pygments.rb )
redcarpet ( https://github.com/vmg/redcarpet )
markdown-rails ( https://github.com/joliss/markdown-rails )

設定步驟如下

1. Gemfile 設定

添加必要的 gem 套件至 Gemfile 檔中

Gemfile
# Use markdown template

gem 'markdown-rails'

# support markdown & syntax highlighter

gem 'redcarpet'
gem 'pygments.rb'

2. Config 設定

新增 config/initializers/markdown.rb
class HTMLWithPygments < Redcarpet::Render::HTML
  def block_code(code, language)
    sha = Digest::SHA1.hexdigest(code)
    Rails.cache.fetch ["code", language, sha].join('-') do
      Pygments.highlight(code, lexer: language)
    end
  end
end

MarkdownRails.configure do |config|
  config.render do |markdown_source|
    renderer = HTMLWithPygments.new(hard_wrap: true, filter_html: true)
    options = {
        autolink: true,
        no_intra_emphasis: true,
        fenced_code_blocks: true,
        lax_html_blocks: true,
        strikethrough: true,
        superscript: true
    }
    Redcarpet::Markdown.new(renderer, options).render(markdown_source).html_safe
  end
end

3. CSS 設定

新增 app/assets/stylesheets/pygments.css.erb
<%= Pygments.css(style: "igor") %>

備註:style 的部分就看個人喜好設定,style 的種類可以使用以下方式查看

$ rails c
Loading development environment (Rails 4.1.8)
irb(main):001:0> Pygments.styles
=> ["manni", "igor", "xcode", "vim", "autumn", "vs", "rrt", "native", "perldoc", "borland", "tango", "emacs", "friendly", "monokai", "paraiso-dark", "colorful", "murphy", "bw", "pastie", "paraiso-light", "trac", "default", "fruity"]
修改 app/assets/stylesheets/application.css.scss
 ...

 *= require pygments

 ...

 *= require_self

這個地方筆者是把原本預設的 require_tree . 拿掉,所以,需要額外呼叫,就看個人喜好摟!

4. View 設定

新增任意對應 action 的 view 檔案,格式為 action_name.html.md,重啟伺服器之後就搞定了!!

← Ruby on Rails 中使用 Google QR Code 生成器 使用 Better Errors 和 Rails Panel 讓除錯更輕鬆快速 →
 
comments powered by Disqus