Forum: Ruby Redirecting CGI#out to a string

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
unknown (Guest)
on 2006-01-05 13:08
(Received via mailing list)
Hi All

For my first "production" ruby app, I'm writing a self contained web
interface to the TSM backup product, based on some existing, awful,
perl code.  I'm using webrick because the number of requests will be
small, and I want it cross platform and as self-contained as possible.

I'd prefer to generate my html using the CGI class, but webrick needs a
string to be returned and CGI#out writes to standard output.

I've played with redirecting $stdout to a StringIO object, but haven't
been able to get that to work, and also that doesn't seem to be the
Ruby way, its more Perl-ish.

Can some kind soul please point me in the right direction?

TIA

Steve.

AIX and TSM Administrator
Brisbane Australia
Ross B. (Guest)
on 2006-01-05 14:00
(Received via mailing list)
On Thu, 05 Jan 2006 11:05:01 -0000, <removed_email_address@domain.invalid> 
wrote:

> I'd prefer to generate my html using the CGI class, but webrick needs a
> string to be returned and CGI#out writes to standard output.
>

I've not used CGI much myself, but a quick experiment yielded this:

	require 'cgi'

	cgi = CGI.new('html4')
	html = cgi.html do
	  cgi.body do
	    cgi.pre do
	      "Don't use 'out'"
	    end
	  end
	end

	# Now you can do what you want with it, for example:
	puts CGI.pretty(html.gsub(/<([^!][^>]*)>/) { "<#{$1.downcase}>" })

Outputs:

	<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
	<html>
	  <body>
	    <pre>
	      Don't use 'out'
	    </pre>
	  </body>
	</html>

I don't know if it's the best tool for your task, but anyway I hope that
helps...
This topic is locked and can not be replied to.