# Redirecting CGI#out to a string

**URL:** <https://www.ruby-forum.com/t/redirecting-cgi-out-to-a-string/90101>\
**Category:** Ruby\
**Created:** [January 5, 2006, 12:08pm UTC](https://www.ruby-forum.com/t/redirecting-cgi-out-to-a-string/90101 "2006-01-05T12:08:58Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 5, 2006, 12:08pm UTC](https://www.ruby-forum.com/t/redirecting-cgi-out-to-a-string/90101/1 "2006-01-05T12:08:58Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![unknown](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/4bbf92/32.png) [@unknown](https://www.ruby-forum.com/u/unknown)\
**Post date:** [January 5, 2006, 1:00pm UTC](https://www.ruby-forum.com/t/redirecting-cgi-out-to-a-string/90101/2 "2006-01-05T13:00:07Z")

</div>

On Thu, 05 Jan 2006 11:05:01 -0000, [removed\_email\_address@domain.invalid](mailto: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](http://www.w3.org/TR/html4/strict.dtd)”\>

```
Don’t use ‘out’
```
  
  

I don’t know if it’s the best tool for your task, but anyway I hope that  
helps…
