almost 4 years ago

系統:

Mac OS X Yosemite 10.10.1
Ruby 2.1.5
Rails 4.1.8

相關連結

pygments ( http://pygments.org/ )
pygments.rb ( https://github.com/tmm1/pygments.rb )
redcarpet ( https://github.com/vmg/redcarpet )

設定步驟如下

1. Gemfile 設定

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

# support markdown & syntax highlighter
gem 'redcarpet'
gem 'pygments.rb'

Helper 設定

app/helpers/markdown_helper.rb

module MarkdownHelper
  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

  def markdown(text)
    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(text).html_safe
  end
end

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 . 拿掉,所以,需要額外呼叫,就看個人喜好摟!

View 設定

app/views/posts/show.html.slim

.content

  = markdown @post.content
← 使用 Vagrant 和 Chef 開發 Rails - Part 3 - Site Cookbook Post 管理 - part 5 - Paginator →
 
comments powered by Disqus