MathJax を使って YARD で数式が入ったドキュメントを書く

先日、同目的で Sphinx の使い方について調べた。

しかしやっぱり YARD がよかろうともう少し調べてみた。
ヘッダで js ファイルを読み込み、ウェブページ内に記載されている数式を LaTeX で表示してくれる MathJax を使ってみることにします。

ここでのポイントは

  • ヘッダで読み込むように YARD のテンプレートを弄る必要がある
  • テンプレートを利用するように yard のオプションを付記する

テンプレートの編集

$ mkdir lib
$ mkdir templates
$ 
$ # yard の場所を調べる
$ gem which yard
/usr/local/rvm/gems/ruby-1.9.3-p448/gems/yard-0.8.7/lib/yard.rb
$
$ # そこにある default テンプレートをコピー
$ cp -r /usr/local/rvm/gems/ruby-1.9.3-p448/gems/yard-0.8.7/templates/default templates/mathjax

rvm を使っているため、通常とは格納場所は少し違っています。

次の2つのファイルを編集します。

  • templates/mathjax/layout/html/layout.erb
  • templates/mathjax/onefile/html/layout.erb
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=<%= charset %>" />
  <title><%= @title %></title>
  <%= erb(:headers) %>
  <!-- ここから -->
  <script type="text/x-mathjax-config">
    MathJax.Hub.Config({
      tex2jax:{
        inlineMath: [ ['$','$'], ["\\(","\\)"] ],
        displayMath: [ ['$$','$$'], ["\\[","\\]"] ]
      }
    });
  </script>
  <script type="text/javascript"
    src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML">
  </script>
  <meta http-equiv="X-UA-Compatible" CONTENT="IE=EmulateIE7" />
  <!-- ここまでを挿入 -->
</head>

yard のオプション

プロジェクトディレクトリや gem ファイルのルートに .yardopts を用意して、自動的にオプションが付加されるようにします。

たとえば

-t mathjax -p templates lib/*.rb - README.md

RubyGems.org からリンクされているドキュメントは RubyDoc.info によるものですが、 RubyDoc.info に .yardopts の記事があるため、 RubyGems にプッシュしたときも意図通りに反映されるものと思われます(未確認)。

.yardopts に関しては

ドキュメントを書く

# MyMath
module MyMath
  # Returns cosine
  #
  # @param [Float] theta $\\theta$
  # @return [Float] $\\cos(\\theta)$
  def cos(theta = 0.0)
    Math::cos(theta)
  end
end

一旦 YARD の処理が挟まるためか、バックスラッシュを二重にしてエスケープする必要があるようです。