Hi Robert, 

On Mon, 2 Aug 2004 05:06:39 +0900, Robert <catcher / linuxmail.org> wrote:
> What do you use when programming Ruby/CGI? Do you just use straight Ruby or
> do you use any templating modules?

Here is a tiny template ``engine'' I use that creates a Struct class
and defines its #to_s method:
 
| class StructTemplate
|   TEMPLATES = {}
|   def StructTemplate.new(template, *args)
|     klass = Struct.new(*args)
|     TEMPLATES[klass] = template.to_s
|     klass.class_eval do
|       def to_s
|         TEMPLATES[self.class].gsub(/\#\{(.*?)\}/) do
|           method($1).call.to_s if respond_to? $1
|         end
|       end
|     end
|     klass
|   end
| end

You might have a file template that looks like this (let's call it
``page.tmpl''):

| <html>
|   <head>
|     <title>#{title}</title>
|   </head>
|   <body>
|     #{content}
|   </body>
| </html>

Then you could use it like this:

| require 'cgi'
| cgi = CGI.new
| PageT = StructTemplate.new('page.tmpl', :title, :content)
|
| page = PageT.new
| page.title = 'Hello World!'
| page.content = 'Content goes here'
| cgi.out {page}

Since StructTemplate#to_s calls #to_s on each member as it's being
substituted into the template, you can create fairly complex output by
nesting templates. If you have a page with many ``objects'' that are
alike (say, for instance, a weblog with multiple ``entries''), you can
create StructTemplates for those objects and pass an array of them to
the page template for its content.

It's not advanced by any means, but it's certainly simple and
relatively easy to use.

> Robert

Sam