# Tiny Tiny eRuby --- Utility 
# 	Copyright (c) 2000,2002 Masatoshi SEKI 
#       You can redistribute it and/or modify it under the same term as Ruby.

require 'erb/erbl'

module ERbUtil
  class BGAttr
    def initialize(colors = ["#eeeeee", "#ffffff"])
      @colors = colors
      @cur = -1
    end

    public
    def succ
      @cur = (@cur+1) % @colors.size
    end
    
    public
    def to_s
      succ
      "bgcolor=\"#{@colors[@cur]}\""
    end
  end

  public
  def html_escape(s)
    s.to_s.gsub(/&/, "&amp;").gsub(/\"/, "&quot;").gsub(/>/, "&gt;").gsub(/</, "&lt;")
  end
  alias h html_escape

  def url_encode(s)
    s.to_s.gsub(/[^a-zA-Z0-9_\-.]/n){ sprintf("%%%02X", $&.unpack("C")[0]) }
  end
  alias u url_encode
end

class ERbLight
  def def_method(mod, methodname, fname='(ERbLight)')
    mod.module_eval("def #{methodname}\n" + self.src + "\nend\n", fname, 0)
  end

  def def_module(methodname='erb')
    mod = Module.new
    def_method(mod, methodname)
    mod
  end

  def def_class(superklass=Object, methodname='result')
    cls = Class.new
    def_method(cls, methodname)
    cls
  end
end

module ERbMethod
  public
  def def_erb_method(methodname, erb)
    if erb.kind_of? String
      fname = erb
      File.open(fname) {|f| erb = ERbLight.new(f.read) }
    end
    erb.def_method(self, methodname, fname)
  end
  module_function :def_erb_method
end

