LoginSignup
28
27

More than 5 years have passed since last update.

Rubyのヒアドキュメントの代わりにERBを使う

Last updated at Posted at 2014-11-07

長めの文字列に変数を埋め込んで生成したい場合に、ヒアドキュメントで以下のようにやっていたんですが

class ProductDecorator
  def spec_table_html
    <<-HTML
      <table>
        <tr>
          <th>Height</th>
          <td><%= height %></td>
        </tr>
        <tr>
          <th>Width</th>
          <td><%= width %></td>
        </tr>
      </table>
    HTML
  end
end

見づらいし、ruby内の文字列だからhtmlのシンタックスハイライト効かないしイケてないのでERB使って別ファイルにしました

ERBはrequire 'erb'して使うんですが、Railsなら既に読み込んでると思います

使い方はこう(@hnakamurさんのコメントを受けてERB#resultに修正)

class ProductDecorator
  def spec_table_html
    # テンプレートファイルを開く
    erb = Rails.root.join('path/to/template.html.erb').read
    # ERBを走らせる
    ERB.new(erb).result(binding)
  end
end

最初ERB#runの返り値がhtmlになるのかと思ったんですが何も返さなくて、結果を受け取るローカル変数の名前を渡すんですね

ERB#resultで結果を返せるんですね!

肝心の埋め込む変数なんですが、#runの引数にBindingオブジェクトを渡すとそのコンテキストで実行してくれるのでクラス内のメソッドを使ってくれます

なんかPHPのob_start()を思い出しました

28
27
2

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
28
27