singleton method ERB.new

new(str, trim_mode: nil, eoutvar: '_erbout') -> ERB[permalink][rdoc][edit]

eRubyスクリプト から ERB オブジェクトを生成して返します。

[PARAM] str:
eRubyスクリプトを表す文字列
[PARAM] trim_mode:
整形の挙動を変更するオプション
[PARAM] eoutvar:
eRubyスクリプトの中で出力をためていく変数の名前を表す文字列。eRuby スクリプトの中でさらに ERB を使うときに変更します。通常は指定する必要はありません。


require "erb"

# build data class
class Listings
  PRODUCT = { :name => "Chicken Fried Steak",
              :desc => "A well messages pattie, breaded and fried.",
              :cost => 9.95 }

  attr_reader :product, :price

  def initialize( product = "", price = "" )
    @product = product
    @price = price
  end

  def build
    b = binding
    # create and run templates, filling member data variables
    ERB.new(<<~'END_PRODUCT', eoutvar: "@product").result b
      <%= PRODUCT[:name] %>
      <%= PRODUCT[:desc] %>
    END_PRODUCT
    ERB.new(<<~'END_PRICE', eoutvar: "@price").result b
      <%= PRODUCT[:name] %> -- <%= PRODUCT[:cost] %>
      <%= PRODUCT[:desc] %>
    END_PRICE
  end
end

# setup template data
listings = Listings.new
listings.build

puts listings.product + "\n" + listings.price

# Chicken Fried Steak
# A well messages pattie, breaded and fried.
# 
# Chicken Fried Steak -- 9.95
# A well messages pattie, breaded and fried.