Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | 1ファイルで完結する使い捨ての処理で__END__とERBを組み合わせる

概要

1ファイルで完結する使い捨ての処理で__END__とERBを組み合わせる

詳細

__END__はそれ以降の文字列をコメントとして扱います。
そしてDATA定数で__END__以降の文字列を取得出来ます。

これを利用してERBを利用したテンプレート処理を作ってみます。

サンプルコード

# encoding: utf-8
require "erb"

class EndERB
  class << self
    def apply(hash)
      ERB.new(DATA.read).result(binding)
    end
  end
end

hash = {
  sub_title1: '',
  sub_title2: '悪霊の神々',
  sub_title3: 'そして伝説へ…',
}
puts EndERB.apply(hash)

__END__
ドラクエ1<%=hash[:sub_title1]%>
ドラクエ2<%=hash[:sub_title2]%>
ドラクエ3<%=hash[:sub_title3]%>

出力

ドラクエ1
ドラクエ2悪霊の神々
ドラクエ3そして伝説へ…