eruby.rb

標準添付のERBででっち上げるeRuby処理系。
ファイルからソース読んで貼り付けるための関数とか、
__END__で解釈を打ち切るとかくっ付いた。

module Utils
  def lines(fname, with_lineno=false)
    lines = File.read(fname).rstrip.split("\n")
    if  with_lineno
      lines.each_with_index do |line, i|
        lines[i] = sprintf(" %03d  %s", i + 1, line)
      end
    else
      lines.map!{|line| " #{line}" }
    end
    lines.join("\n")
  end
  module_function :lines
end

require 'erb'
ERB.new(ARGF.read.split(/^__END__$\n/, 2)[0]).run


で、RD+eRubyで書く。
先頭で

<%
@section_nunber = 0

def sec_no
  @section_nunber
end

def section!
  "#{@section_nunber += 1}."
end

def sample(with_lineno = false, &block)
  block ||= lambda{|s| s }
  begin
    Utils.lines("#{block.call(sprintf("%02d", sec_no))}.rb", with_lineno)
  rescue Errno::ENOENT => ex
    ex.message
  end
end
%>

とかして

== <%= section! %> なんかの第一章
なんかのサンプルスクリプト。(01.rbの中身がここに…)
<%= sample %>

その改良版(01a.rbの中身が…)
<%= sample{|s| s + 'a' } %>

なんてしてみたり。

こういうユーティリティをまとめて、RD+eRubyによる文章書きを
システム化すると便利かも知れない(と思うだけでやらない)。