LoginSignup
9
7

More than 5 years have passed since last update.

railsでブログ内にシンタックスハイライト(コードの色付け)をする方法(2)

Last updated at Posted at 2012-12-26

続きましてシンタックスハイライトについてです

シンタックスハイライト


wikiより

シンタックスハイライト(英: Syntax highlighting)とは、テキストエディタの機能であり、テキスト中の一部分をその分類ごとに異なる色やフォントで表示するものである

要はこういうものですね
元のコード
    ↓ シンタックスハイライト!
シンタックスハイライト後のコード

エディターでも使われていて、構文解析を行なって意味によって色付けを行う機能です

Railsではシンタックスハイライト用にいくつかなgemがありますがここでは
・CodeRay

を使用しします。またマークダウンされたコードは<pre></pre>というタグで囲まていて、コードの部分だけを色付けするためには構文解析が必要となり
・nokogiri

というgemを使います。ということで、インストールしましょう!

Gemfile
gem 'redcarpet', '~>1.17.2'
gem 'coderay'
gem 'nokogiri'
Terminal
bundle install

それでは、コード部分をシンタックスハイライトさせましょう。
考え方は
マークダウン→<pre></pre>に囲まれているところを抽出→CodeRayで色をつけたHTMLに置き換える

感じでございます

~helper.rbなど
def markdown(text)
  #optionの設定
  options = [ :autolink, :gh_blockcode, :hard_wrap, :no_intraemphasis,
    :fenced_code, :filter_html]
  #マークダウン
  Redcarpet.new(text, *options).to_html.html_safe
end

def Coderay(code)
  text = markdown(code)
  doc = Nokogiri::HTML(text)
  doc.search("//pre[@lang]").each do |pre|
    pre.replace CodeRay.scan(pre.text.rstrip, pre[:lang]).div(:line_numbers => :table)
  end
  doc.to_html.html_safe
end

これでコントローラーで設定したモデルに(@post)を渡すことで完了です

show.html.erbなど
<%= Coderay(@post.body) %>

以上でございます。お疲れ様でした
参考:Markdown:RAILSCASTS

9
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
7