(Mis-) using the CGI module for (only) generating HTML output

I would like to create a file containing HTML code. This is not part of
a web application, and in particular I am not writing a CGI script.

I could just create the HTML code (using puts(…) statements).

I could also use some HTML template (ERB,…)

I prefer however to use a library which just makes the HTML generation a
bit easier, for example by automatically closing open tags and so.
Things which the cgi module is doing.

However, since I am not in a “real” CGI environment, creating the output
object already has a specific meaning, i.e. running in “offline mode”.
If we try this in irb:

require ‘cgi’
irb(main):019:0> cgi=CGI.new(“html4”)
(offline mode: enter name=value pairs on standard input)


  • Is there a way I could use the cgi module for my task?
  • Are there other ways to solve this?

I’m not understanding what you need.

This script will create HTML based in what?
You’ll save this in DB or just prints on screen?
You want to generate a web page or print all html tags on page like
“View Page Source” ?

Could you give and example of what you already have?

I want to create a HTML file. I could do it simply like this (just an
simplified example to clarify the point):

# Assume that variables 'id' and 'a' have been set before

open('outfile.html','w') do |fh|
    puts <<EOS

Example file generated for #{id}

    EOS list.each do |a| puts "
  • Item #{a[0]}
  • " end puts "" end

    You get the point? Now, while this works, I wanted to find an
    alternative, more convenient way to implement this. After looking around
    a bit, I found a posting where someone suggested to use the CGI class
    for such type of tasks. The cgi module takes care, for example, to
    automatically close opened tags. However, I don’t see how I can get a
    CGI object instantiated, when I’m not in a CGI context, so maybe it was
    a silly idea in the first place, using the cgi module for this task.
    Therefore, if you have other suggestions, please let me know.

Ronald F. wrote in post #1176683:

you need a html builder.
see :


==> “Using Markaby as a Ruby class”

haml is also a good choice :

engine = Haml::Engine.new("%p Haml code!")
engine.render #=> “

Haml code!


Regis d’Aubarede wrote in post #1176703:

you need a html builder.
see :


Thanks a lot for providing all the links. This is exactly what I war
looking for!


This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs