<ppdoc>
<copyright>
    Copyright (c) 2001 by Addison Wesley Longman.  This
    material may be distributed only subject to the terms and
    conditions set forth in the Open Publication License, v1.0 or
    later (the latest version is presently available at
    http://www.opencontent.org/openpub/).
</copyright>
<chapter  ref="xref-000001" name="Ruby and the Web">
<p/>
Ruby is no stranger to the Internet.  Not only can you write your own
SMTP server, FTP daemon, or Web server in Ruby, but you can also use
Ruby for more usual tasks such as CGI programming or as a
replacement for PHP.
<section>Writing CGI Scripts</section>
<p/>
You can use Ruby to write CGI scripts quite easily.  To have a Ruby
script generate HTML output, all you need is
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  #!/usr/bin/env ruby
  print "HTTP/1.0 200 OK\r\n"
  print "Content-type: text/html\r\n\r\n"
  print "<html><body>Hello World!</body></html>\r\n"
]]></fullcode>
#!/usr/bin/env<nbsp/>ruby
print<nbsp/>"HTTP/1.0<nbsp/>200<nbsp/>OK\r\n"
print<nbsp/>"Content-type:<nbsp/>text/html\r\n\r\n"
print<nbsp/>"&lt;html&gt;&lt;body&gt;Hello<nbsp/>World!&lt;/body&gt;&lt;/html&gt;\r\n"
</alltt>
</codefragment>
<p/>
You <em>could</em> use Ruby's regular expression features to parse
incoming query strings, look up environment variables, check tags,
substitute text into templates, escape special characters, format up
the HTML, and print it all out.
<p/>
Or, you could use class <classname>CGI</classname>.
<subsection>Using cgi.rb</subsection>
<p/>
Class <classname>CGI</classname> provides support for writing CGI scripts.  With it, you
can manipulate forms, cookies, and the environment, maintain stateful
sessions, and so on.  It's documented in full in the reference section
beginning on page 497, but we'll take a quick look at its
capabilities here.
<subsection>Quoting</subsection>
<p/>
When dealing with URLs and HTML code, you must be careful to quote
certain characters.  For instance, a slash character (``/'') has
special meaning in a URL, so it must be ``escaped'' if it's not part
of the path name.  That is, any ``/'' in the query portion of the URL
will be translated to the string ``<tt>%2F</tt>'' and must be translated back
to a ``/'' for you to use it.  Space and ampersand are also special
characters. To handle this, <classname>CGI</classname> provides the routines
<ccm><front>CGI</front><back>escape</back></ccm> and <ccm><front>CGI</front><back>unescape</back></ccm>:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'cgi'
  puts CGI.escape( "Nicholas Payton/Trumpet & Flugel Horn" )
]]></fullcode>
require<nbsp/>'cgi'
puts<nbsp/>CGI.escape(<nbsp/>"Nicholas<nbsp/>Payton/Trumpet<nbsp/>&amp;<nbsp/>Flugel<nbsp/>Horn"<nbsp/>)
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Nicholas+Payton%2FTrumpet+%26+Flugel+Horn
</alltt>
</codefragment>
<p/>
Similarly, you may want to escape HTML special characters:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'cgi'
  puts CGI.escapeHTML( '<a href="/mp3">Click Here</a>' )
]]></fullcode>
require<nbsp/>'cgi'
puts<nbsp/>CGI.escapeHTML(<nbsp/>'&lt;a<nbsp/>href="/mp3"&gt;Click<nbsp/>Here&lt;/a&gt;'<nbsp/>)
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
&amp;lt;a<nbsp/>href=&amp;quot;/mp3&amp;quot;&amp;gt;Click<nbsp/>Here&amp;lt;/a&amp;gt;
</alltt>
</codefragment>
<p/>
To get really fancy, you can decide to escape only certain elements
within a string:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require 'cgi'
  puts CGI.escapeElement('<hr><a href="/mp3">Click Here</a><br>','A')
]]></fullcode>
require<nbsp/>'cgi'
puts<nbsp/>CGI.escapeElement('&lt;hr&gt;&lt;a<nbsp/>href="/mp3"&gt;Click<nbsp/>Here&lt;/a&gt;&lt;br&gt;','A')
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
&lt;hr&gt;&amp;lt;a<nbsp/>href=&amp;quot;/mp3&amp;quot;&amp;gt;Click<nbsp/>Here&amp;lt;/a&amp;gt;&lt;br&gt;
</alltt>
</codefragment>
<p/>
Here only the ``<tt>A</tt>'' tag is escaped; other tags are left alone.
Each of these methods has an ``<tt>un</tt>-'' version to restore the original
string.
<subsection>Forms</subsection>
<p/>
Using class <classname>CGI</classname> gives you access to HTML query parameters in two
ways.
Suppose we are given a URL of
<tt>/cgi-bin/lookup?player=Miles%20Davis&amp;year=1958</tt>.  You can access
the parameters ``<tt>player</tt>'' and ``<tt>year</tt>'' using <cim><front>CGI</front><back>[]</back></cim> directly:
<p/>
<codefragment>
<fullcode><![CDATA[!-  $stdin=DATA
  require 'cgi'
  cgi = CGI.new
  cgi['player']
  cgi['year']
!-__END__
!-year=1958
!-player=Miles%20Davis
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>require<nbsp/>'cgi'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>cgi<nbsp/>=<nbsp/>CGI.new</tt></td>
</tr>
<tr>
  <td><tt>cgi['player']</tt></td>
  <td>&#187;</td>
  <td><tt>["Miles<nbsp/>Davis"]</tt></td>
</tr>
<tr>
  <td><tt>cgi['year']</tt></td>
  <td>&#187;</td>
  <td><tt>["1958"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<p/>
Or, you can retrieve all parameters as a <classname>Hash</classname>:
<p/>
<codefragment>
<fullcode><![CDATA[!-  $stdin=DATA
  require 'cgi'
  cgi = CGI.new
  h = cgi.params
  h['player']
!-__END__
!-year=1958
!-player=Miles%20Davis
]]></fullcode><rubycode>
<tr>
<td colspan="3"><tt>require<nbsp/>'cgi'</tt></td>
</tr>
<tr>
<td colspan="3"><tt>cgi<nbsp/>=<nbsp/>CGI.new</tt></td>
</tr>
<tr>
<td colspan="3"><tt>h<nbsp/>=<nbsp/>cgi.params</tt></td>
</tr>
<tr>
  <td><tt>h['player']</tt></td>
  <td>&#187;</td>
  <td><tt>["Miles<nbsp/>Davis"]</tt></td>
</tr>
</rubycode>
<p/>
</codefragment>
<subsubsection>Creating Forms and HTML</subsubsection>
<p/>
<classname>CGI</classname> contains a huge number of methods used to create HTML---one
method per tag.  In order to enable these methods, you must create a
<classname>CGI</classname> object by calling <ccm><front>CGI</front><back>new</back></ccm>, passing in the required level
of HTML.  For these examples, we'll use ``<tt>html3</tt>''.
<p/>
To make tag nesting easier, these methods take their content as code
blocks.  The code blocks should return a <classname>String</classname>, which will be
used as the content for the tag.  For this example, we've added some
gratuitous newlines to make the output fit on the page.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require "cgi"
  cgi = CGI.new("html3")  # add HTML generation methods
  cgi.out{
    cgi.html{
      cgi.head{ "\n"+cgi.title{"This Is a Test"} } +
      cgi.body{ "\n"+
        cgi.form{"\n"+
          cgi.hr +
          cgi.h1 { "A Form: " } + "\n"+
          cgi.textarea("get_text") +"\n"+
          cgi.br +
          cgi.submit
        }
      }
    }
  }
]]></fullcode>
require<nbsp/>"cgi"
cgi<nbsp/>=<nbsp/>CGI.new("html3")<nbsp/><nbsp/>#<nbsp/>add<nbsp/>HTML<nbsp/>generation<nbsp/>methods
cgi.out{
<nbsp/><nbsp/>cgi.html{
<nbsp/><nbsp/><nbsp/><nbsp/>cgi.head{<nbsp/>"\n"+cgi.title{"This<nbsp/>Is<nbsp/>a<nbsp/>Test"}<nbsp/>}<nbsp/>+
<nbsp/><nbsp/><nbsp/><nbsp/>cgi.body{<nbsp/>"\n"+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.form{"\n"+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.hr<nbsp/>+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.h1<nbsp/>{<nbsp/>"A<nbsp/>Form:<nbsp/>"<nbsp/>}<nbsp/>+<nbsp/>"\n"+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.textarea("get_text")<nbsp/>+"\n"+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.br<nbsp/>+
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cgi.submit
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Content-Type:<nbsp/>text/html
Content-Length:<nbsp/>302
<p/>
&lt;!DOCTYPE<nbsp/>HTML<nbsp/>PUBLIC<nbsp/>"-//W3C//DTD<nbsp/>HTML<nbsp/>3.2<nbsp/>Final//EN"&gt;&lt;HTML&gt;&lt;HEAD&gt;
&lt;TITLE&gt;This<nbsp/>Is<nbsp/>a<nbsp/>Test&lt;/TITLE&gt;&lt;/HEAD&gt;&lt;BODY&gt;
&lt;FORM<nbsp/>ENCTYPE="application/x-www-form-urlencoded"<nbsp/>METHOD="post"&gt;
&lt;HR&gt;&lt;H1&gt;A<nbsp/>Form:<nbsp/>&lt;/H1&gt;
&lt;TEXTAREA<nbsp/>NAME="get_text"<nbsp/>COLS="70"<nbsp/>ROWS="10"&gt;&lt;/TEXTAREA&gt;
&lt;BR&gt;&lt;INPUT<nbsp/>TYPE="submit"&gt;&lt;/FORM&gt;&lt;/BODY&gt;&lt;/HTML&gt;
</alltt>
</codefragment>
<p/>
This code will produce an HTML form titled ``This Is a Test,''
followed by a horizontal rule, a level-one header, a test input area,
and finally a submit button.  When the submit comes back, you'll have
a CGI parameter named ``<tt>get_text</tt>'' containing the text the 
user entered.
<subsection>Cookies</subsection>
<p/>
You can store all kinds of interesting stuff on an unsuspecting
surfer's machine using <em>cookies</em>.
You can create a named cookie
object and store a number of values in it.  To send it down to the
browser, set a ``cookie'' header in the call to <cim><front>CGI</front><back>out</back></cim>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  require "cgi"
  cookie = CGI::Cookie.new("rubyweb", "CustID=123", "Part=ABC");
  cgi = CGI.new("html3")
  cgi.out( "cookie" => [cookie] ){ 
    cgi.html{
      "\nHTML content here"
    } 
  }
]]></fullcode>
require<nbsp/>"cgi"
cookie<nbsp/>=<nbsp/>CGI::Cookie.new("rubyweb",<nbsp/>"CustID=123",<nbsp/>"Part=ABC");
cgi<nbsp/>=<nbsp/>CGI.new("html3")
cgi.out(<nbsp/>"cookie"<nbsp/>=&gt;<nbsp/>[cookie]<nbsp/>){
<nbsp/><nbsp/>cgi.html{
<nbsp/><nbsp/><nbsp/><nbsp/>"\nHTML<nbsp/>content<nbsp/>here"
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Content-Type:<nbsp/>text/html
Content-Length:<nbsp/>86
Set-Cookie:<nbsp/>rubyweb=CustID%3D123&amp;Part%3DABC;<nbsp/>path=
<p/>
&lt;!DOCTYPE<nbsp/>HTML<nbsp/>PUBLIC<nbsp/>"-//W3C//DTD<nbsp/>HTML<nbsp/>3.2<nbsp/>Final//EN"&gt;&lt;HTML&gt;
HTML<nbsp/>content<nbsp/>here&lt;/HTML&gt;
</alltt>
</codefragment>
<p/>
The next time the user comes back to this page, you can retrieve
the cookie values for <tt>CustID</tt> and <tt>Part</tt>, as shown in the
HTML output.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-ENV["HTTP_COOKIE"]="rubyweb=CustID%3D123&Part%3DABC"
  require "cgi"
  cgi = CGI.new("html3")
  cgi.out{
    cgi.html{
      cgi.pre{
        cookie = cgi.cookies["rubyweb"]
          "\nCookies are\n" + cookie.value.join("\n")
      }
    } 
  }
]]></fullcode>
require<nbsp/>"cgi"
cgi<nbsp/>=<nbsp/>CGI.new("html3")
cgi.out{
<nbsp/><nbsp/>cgi.html{
<nbsp/><nbsp/><nbsp/><nbsp/>cgi.pre{
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>cookie<nbsp/>=<nbsp/>cgi.cookies["rubyweb"]
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"\nCookies<nbsp/>are\n"<nbsp/>+<nbsp/>cookie.value.join("\n")
<nbsp/><nbsp/><nbsp/><nbsp/>}
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<em>produces:</em>
<codefragment><alltt>
Content-Type:<nbsp/>text/html
Content-Length:<nbsp/>111
<p/>
&lt;!DOCTYPE<nbsp/>HTML<nbsp/>PUBLIC<nbsp/>"-//W3C//DTD<nbsp/>HTML<nbsp/>3.2<nbsp/>Final//EN"&gt;&lt;HTML&gt;&lt;PRE&gt;
Cookies<nbsp/>are
CustID=123
Part=ABC&lt;/PRE&gt;&lt;/HTML&gt;
</alltt>
</codefragment>
<subsection>Sessions</subsection>
<p/>
Cookies by themselves still need a bit of work to be useful.
What
we really want is a <em>session:</em> a persistent state for some Web
surfer.  Sessions are handled with <classname>CGI::Session</classname>
(documented beginning on page 504), which uses cookies
but provides a higher-level abstraction.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[
  require "cgi"
  require "cgi/session"

  cgi = CGI.new("html3")
  sess = CGI::Session.new( cgi, "session_key" => "rubyweb",
                            "session_id"  => "9650",
                            "new_session" => true,
                            "prefix" => "web-session.")
  sess["CustID"] = 123
  sess["Part"] = "ABC"

  cgi.out{
    cgi.html{
      "\nHTML content here"
    } 
  }
]]></fullcode>
<p/>
require<nbsp/>"cgi"
require<nbsp/>"cgi/session"
<p/>
cgi<nbsp/>=<nbsp/>CGI.new("html3")
sess<nbsp/>=<nbsp/>CGI::Session.new(<nbsp/>cgi,<nbsp/>"session_key"<nbsp/>=&gt;<nbsp/>"rubyweb",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"session_id"<nbsp/><nbsp/>=&gt;<nbsp/>"9650",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"new_session"<nbsp/>=&gt;<nbsp/>true,
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"prefix"<nbsp/>=&gt;<nbsp/>"web-session.")
sess["CustID"]<nbsp/>=<nbsp/>123
sess["Part"]<nbsp/>=<nbsp/>"ABC"
<p/>
cgi.out{
<nbsp/><nbsp/>cgi.html{
<nbsp/><nbsp/><nbsp/><nbsp/>"\nHTML<nbsp/>content<nbsp/>here"
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<p/>
This will send a cookie to the user named ``rubyweb'' with a value of
9650.  It will also create a disk file in <tt>$TMP/web-session.9650</tt>
with the <em>key, value</em> pairs for <tt>CustID</tt> and <tt>Part</tt>.
<p/>
When the user returns, all you need is a parameter to indicate the
session id. In this example, that would be <tt>rubyweb=9650</tt>.  With
that value in the parameters, you'll be able to retrieve the full
set of saved session data.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[!-$stdin=DATA
  require "cgi"
  require "cgi/session"

  cgi = CGI.new("html3")
  sess = CGI::Session.new( cgi, "session_key" => "rubyweb",
                                 "prefix" => "web-session.")
  cgi.out{
    cgi.html{
      "\nCustomer #{sess['CustID']} orders an #{sess['Part']}"
    } 
  }
!-__END__
!-rubyweb=9650
]]></fullcode>
require<nbsp/>"cgi"
require<nbsp/>"cgi/session"
<p/>
cgi<nbsp/>=<nbsp/>CGI.new("html3")
sess<nbsp/>=<nbsp/>CGI::Session.new(<nbsp/>cgi,<nbsp/>"session_key"<nbsp/>=&gt;<nbsp/>"rubyweb",
<nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/><nbsp/>"prefix"<nbsp/>=&gt;<nbsp/>"web-session.")
cgi.out{
<nbsp/><nbsp/>cgi.html{
<nbsp/><nbsp/><nbsp/><nbsp/>"\nCustomer<nbsp/>#{sess['CustID']}<nbsp/>orders<nbsp/>an<nbsp/>#{sess['Part']}"
<nbsp/><nbsp/>}
}
</alltt>
</codefragment>
<section>Embedding Ruby in HTML</section>
<p/>
So far we've looked at using Ruby to create HTML output, but we can
turn the problem inside out; we can actually embed Ruby in an HTML
document.
<p/>
There are a number of packages that allow you to embed Ruby
statements in some other sort of a document, especially in an HTML
page. Generically, this is known as ``eRuby.''  Specifically, there
are several different implementations of eRuby, including <tt>eruby</tt>
and <tt>erb</tt>.  The remainder of this section will discuss <tt>eruby</tt>,
written by Shugo Maeda.
<p/>
Embedding Ruby in HTML is a very powerful concept---it basically gives
us the equivalent of a tool such as ASP, JSP, or PHP, but with the
full power of Ruby.
<subsection>Using eruby</subsection>
<p/>
<tt>eruby</tt> acts as a filter, plain and simple.  Any text within the input
file is passed through untouched, with the following exceptions:
<p/>
<table>
<th>
  <td><b>Expression</b></td>
  <td><b>Description</b></td>
</th>
<tr>
  <td><tt>&lt;%</tt> <em>ruby code</em> <tt>%&gt;</tt></td>
  <td>The Ruby code between the delimiters 
  is replaced with its output.</td>
</tr>
<tr>
  <td><tt>&lt;%=</tt> <em>ruby expression</em> <tt>%&gt;</tt></td>
  <td>The Ruby expression
  between the delimiters is replaced with its value.</td>
</tr>
<tr>
  <td><tt>&lt;%#</tt> <em>ruby code</em> <tt>%&gt;</tt></td>
  <td>The Ruby code between the
  delimiters is ignored (useful for testing).</td>
</tr>
<bottomrule/></table>
<p/>
You invoke <tt>eruby</tt> as:
<p/>
<syntax>
eruby <opt><nt>options</nt></opt> <opt><nt>document</nt></opt>
</syntax>
<p/>
If the <em>document</em> is omitted, <tt>eruby</tt> will read from standard
input.  The command-line options for <tt>eruby</tt> are shown in Table
14.1 on page 149.
<figure type="table">
<caption>Command-line options for <tt>eruby</tt></caption>
<table>
<th>
  <td><b>Option</b></td>
  <td><b>Description</b></td>
</th>
<tr>
  <td><tt>-d</tt>, <tt>--debug</tt></td>
  <td>Sets $DEBUG to <tt>true</tt>.</td>
</tr>
<tr>
  <td><tt>-K</tt><em>kcode</em></td>
  <td>Specifies an alternate coding system
                                    (see page 137).</td>
</tr>
<tr>
  <td><tt>-M</tt><em>mode</em></td>
  <td>Specifies runtime <em>mode</em>, one of:
<p/>
  <table>
<tr>
  <td><tt>f</tt></td>
  <td>filter mode</td>
</tr>
<tr>
  <td><tt>c</tt></td>
  <td>CGI mode (prints errors as HTML, sets $SAFE=1)</td>
</tr>
<tr>
  <td><tt>n</tt></td>
  <td>NPH-CGI mode (prints extra HTTP headers, sets $SAFE=1)</td>
</tr>
<tr>
  <td></td>
</tr>
</table>
</td>
</tr>
<tr>
  <td><tt>-n</tt>, <tt>--noheader</tt></td>
  <td>Disables CGI header output.</td>
</tr>
<tr>
  <td><tt>-v</tt>, <tt>--verbose</tt></td>
  <td>Enables verbose mode.</td>
</tr>
<tr>
  <td><tt>--version</tt></td>
  <td>Prints version information and exits.</td>
</tr>
<bottomrule/></table>
<p/>
</figure>
<p/>
Let's look at some simple examples.  We'll run the <tt>eruby</tt> executable 
on the following input.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  This text is <% a = 100; puts "#{a}% Live!" %>
]]></fullcode>
This<nbsp/>text<nbsp/>is<nbsp/>&lt;%<nbsp/>a<nbsp/>=<nbsp/>100;<nbsp/>puts<nbsp/>"#{a}%<nbsp/>Live!"<nbsp/>%&gt;
</alltt>
</codefragment>
<p/>
<tt>eruby</tt> substitutes the expression between the delimiters and
produces
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  This text is 100% Live!
]]></fullcode>
This<nbsp/>text<nbsp/>is<nbsp/>100%<nbsp/>Live!
</alltt>
</codefragment>
<p/>
Using the &lt;%= form acts as if you printed the value of the
expression.  For instance, the input
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  <%a = 100%>This text is almost <%=a%> degrees! Cool!
]]></fullcode>
&lt;%a<nbsp/>=<nbsp/>100%&gt;This<nbsp/>text<nbsp/>is<nbsp/>almost<nbsp/>&lt;%=a%&gt;<nbsp/>degrees!<nbsp/>Cool!
</alltt>
</codefragment>
<p/>
replaces the <tt>=a</tt> with the value of <tt>a</tt>.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  This text is almost 100 degrees! Cool!
]]></fullcode>
This<nbsp/>text<nbsp/>is<nbsp/>almost<nbsp/>100<nbsp/>degrees!<nbsp/>Cool!
</alltt>
</codefragment>
<p/>
And, of course, you can embed Ruby within a more complex document type,
such as HTML.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN">
<html>
<head>
<title>eruby example</title>
</head>
<body>
<h1>Enumeration</h1>
<ul>
<%(1..10).each do|i|%>
  <li>number <%=i%></li>
<%end%>
</ul>
<h1>Environment variables</h1>
<table>
<%ENV.keys.sort.each do |key|%>
  <tr>
    <th><%=key%></th><td><%=ENV[key]%></td>
  </tr>
<%end%>
</table>
</body>
</html>
]]></fullcode>
&lt;!DOCTYPE<nbsp/>HTML<nbsp/>PUBLIC<nbsp/>"-//W3C//DTD<nbsp/>HTML<nbsp/>4.01//EN"&gt;
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;eruby<nbsp/>example&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Enumeration&lt;/h1&gt;
&lt;ul&gt;
&lt;%(1..10).each<nbsp/>do|i|%&gt;
<nbsp/><nbsp/>&lt;li&gt;number<nbsp/>&lt;%=i%&gt;&lt;/li&gt;
&lt;%end%&gt;
&lt;/ul&gt;
&lt;h1&gt;Environment<nbsp/>variables&lt;/h1&gt;
&lt;table&gt;
&lt;%ENV.keys.sort.each<nbsp/>do<nbsp/>|key|%&gt;
<nbsp/><nbsp/>&lt;tr&gt;
<nbsp/><nbsp/><nbsp/><nbsp/>&lt;th&gt;&lt;%=key%&gt;&lt;/th&gt;&lt;td&gt;&lt;%=ENV[key]%&gt;&lt;/td&gt;
<nbsp/><nbsp/>&lt;/tr&gt;
&lt;%end%&gt;
&lt;/table&gt;
&lt;/body&gt;
&lt;/html&gt;
</alltt>
</codefragment>
<subsection>Installing eruby in Apache</subsection>
<p/>
You can set up an Apache Web server to automatically parse
Ruby-embedded documents using eRuby, much in the same way that PHP
does.  You create Ruby-embedded files with an ``<tt>.rhtml</tt>'' suffix
and configure the Web server to run the <tt>eruby</tt> executable on these
documents to produce the desired HTML output.
<p/>
In order to use <tt>eruby</tt> with the Apache Web server, you need to
perform the following steps.
<p/>
<ul>
  <li> Copy the <tt>eruby</tt> binary to the <tt>cgi-bin</tt> directory.
<p/>
  </li><li> Add the following two lines to <tt>httpd.conf</tt>:
<p/>
<codefragment>
<alltt><fullcode><![CDATA[    AddType application/x-httpd-eruby .rhtml
    Action application/x-httpd-eruby /cgi-bin/eruby
]]></fullcode>
AddType<nbsp/>application/x-httpd-eruby<nbsp/>.rhtml
Action<nbsp/>application/x-httpd-eruby<nbsp/>/cgi-bin/eruby
</alltt>
</codefragment>
<p/>
</li><li> If desired, you can also add or replace the <tt>DirectoryIndex</tt>
  directive such that it includes <tt>index.rhtml</tt>.  This lets you use
  Ruby to create directory listings for directories that do not
  contain an <tt>index.html</tt>.  For instance, the following directive
  would cause the embedded Ruby script <tt>index.rhtml</tt> to be searched
  for and served if neither <tt>index.html</tt> nor <tt>index.shtml</tt> existed in a
  directory.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  DirectoryIndex index.html index.shtml index.rhtml
]]></fullcode>
DirectoryIndex<nbsp/>index.html<nbsp/>index.shtml<nbsp/>index.rhtml
</alltt>
</codefragment>
<p/>
  Of course, you could also simply use a site-wide Ruby script as
  well.
<p/>
<codefragment>
<alltt><fullcode><![CDATA[  DirectoryIndex index.html index.shtml /cgi-bin/index.rb
]]></fullcode>
DirectoryIndex<nbsp/>index.html<nbsp/>index.shtml<nbsp/>/cgi-bin/index.rb
</alltt>
</codefragment>
<p/>
</li></ul>
<p/>
And that's it!  You can now write HTML documents that contain embedded
Ruby to generate forms and content dynamically.  Be sure to see also
the Ruby <classname>CGI</classname> library, which is documented
beginning on page 497.  
<section>Improving Performance</section>
<p/>
You can use Ruby to write CGI programs for the Web, but, as with most
CGI programs, the default configuration has to start up a new copy of
Ruby with every cgi-bin page access.
That's expensive in terms of
machine utilization and can be painfully slow for Web surfers.  
The Apache Web server solves this problem by allowing loadable
<em>modules</em>.
<p/>
Typically, these modules are dynamically loaded and become part of the 
running Web server process---there is no need to spawn
another interpreter over and over again to service requests; the Web
server <em>is</em> the interpreter.
<p/>
And so we come to <tt>mod_ruby</tt> (available from the archives), an
Apache module that links a full Ruby interpreter into the Apache Web
server itself.  The <tt>README</tt> file included with <tt>mod_ruby</tt> provides
details on how to compile and install it.
<p/>
Once installed and configured, you can run Ruby scripts just like you
could without <tt>mod_ruby</tt>, except that now they will come up much
faster.
<p/>
</chapter>
</ppdoc>
