Table of Contents
List of Examples
Table of Contents
There are two ways to use ruby-web: as a replacement for cgi.rb, and as an extension to the Ruby interpreter. Installing ruby-web as a library is simple, and gives one access to the useful functions of ruby-web. There are a few additional features which can be provided at a higher level.
Both the library and interpreter installations of ruby-web depend on Ruby 1.8.x.
Scaling options include:
All of the above, plus:
puts 'Hello, World'
ruby-web source code and binary distributions can be found at http://rubyforge.org/frs/?group_id=873.
Finally, please note that these install instructions are a work in progress. Please report any problems at http://rubyforge.org/tracker/?group_id=873, so that we can solve your problem, and improve.
The simplest way to install ruby-web is to install the gem:
% gem install ruby-web
Then, you can use ruby-web in your cgi programs:
#!/usr/bin/env ruby require 'rubygems' require_gem 'ruby-web' Web::open do puts "Hello World" end
Another way to install ruby-web as a library is to use the tar.gz distribution
% tar -xvzf ruby-web_x.x.x.tar.gz
% cd ruby-web_x.x.x
% ruby install.rb config
% ruby install.rb setup
% ruby install.rb install
Similar to above, you can now use ruby-web in your cgi programs:
#!/usr/bin/env ruby require 'web' Web::open do puts "Hello World" end
Note: for compatibility with cgi.rb:
require "web/shim/cgi"
Note: this this does compile and install the ruby-web interpreter, but you are free to ignore it.
Note: these examples are compatible with FastCGI and mod_ruby. Configure your webserver, and in the case of fastcgi, install the fastcgi ruby libraries. Ruby-web will detect the server environment and run appropriately.
Download the latest ruby-web_x.x.x.tar.gz. Run the enclosed installer:
% cd ruby-web_x.x.x % ruby install.rb config % ruby install.rb setup % ruby install.rb install
This will compile and install the ruby-web interpreter into the same directory as ruby. If you are running ruby-web as a cgi, all you need to do is swap ruby-web for ruby:
#!/usr/bin/ruby-web puts 'Hello, World'
After configuring ruby-web as the interpreter, you need the library to run fastcgi.
You will still need to do the standard FastCGI config on your webserver. You can find a links to extensions for Apache and other web servers at http://www.fastcgi.com
To use the ruby-web interpreter with mod_ruby, there is a slightly different configuration for http.conf:
<IfModule mod_ruby.c>
RubySafeLevel 0
# for Web::RubyRun
RubyRequire web/sapi/apache
<Location / >
Options Indexes FollowSymLinks ExecCGI
AddHandler ruby-object cgi rb rhtml
RubyHandler Web::RubyRun.instance
</Location>
</IfModule>
ruby-web provides a Web::RubyWebHandler, based on the CGIHandler, to run ruby-web scripts. You will need to add the Web::RubyWebHandler to webrick with a startup script like this, replacing :DocumentRoot with the appropriate value:
#!/usr/local/bin/ruby
$: << File.dirname($0)
require 'webrick'
require 'web/sapi/webrick'
include WEBrick
# These lines configure webrick to handle .rb and .rhtml files with ruby-web
HTTPServlet::FileHandler.add_handler("rb", Web::RubyWebHandler)
HTTPServlet::FileHandler.add_handler("rhtml", Web::RubyWebHandler)
s = HTTPServer.new(:Port => 80,
:DocumentRoot => "./htdocs" )
trap("INT"){ s.shutdown }
s.start
Table of Contents
FastCGI is an great way to scale on Windows, but compiling the ruby fcgi bindings on ruby is difficult. There are various distributions of pre-compiled ruby fcgi bindings, but I do not know which ones to recommend.
The Windows ruby-web installer is available from the downloads page at http://rubyforge.org/frs/?group_id=873. This installs ruby-web and for IIS, Apache 1.x, and Apache 2.x, it also configures the web server to run .rb and .rhtml scripts using the CGI version of ruby-web.
First, install your selected HTTP (web) server on your system, and make sure that it works.
The installation wizard gathers enough information to set up the ruby-web, and configure certain web servers to use ruby-web as a cgi.
Once the installation has completed, the installer will restart the server, and you should be ready to just start using ruby-web.
This install guide will help you manually install and configure ruby-web with a web server on Microsoft Windows. Although we distribute a ruby-web installer for Microsoft Windows, you might want to take to setup ruby-web yourself as this will provide you with a better understanding of the system.
To get started you'll need to download
the tar.gz distribution from the downloads page at
http://rubyforge.org/frs/?group_id=873.
If you have not already done so, you will need to install the
Ruby One Click installer
in the directory of your choice. You may choose
a different location but do not have spaces in the
path (like C:\Program Files\Ruby)
as some web servers will crash properly if you do.
Extract the archive (using a program like Winzip) . From the command line, execute these commands:
ruby.exe install.rb config ruby.exe install.rb setup ruby.exe install.rb install
If you're using NTFS on Windows NT, 2000, XP or 2003, make sure that the user running the web server has read permissions to your ruby lib directories (e.g. make c:/ruby/bin and c:/ruby/lib readable by Everyone).
ruby-web is now setup on your system. The next step is to configure your webserver to run ruby-web.
This section contains notes and hints specific to IIS (Microsoft Internet Information Server).
ruby-web.exe
You need to start the Microsoft Management Console (may appear as 'Internet Services Manager', either in your Windows NT 4.0 Option Pack branch or the Control Panel=>Administrative Tools under Windows 2000/XP). Then right click on your Web server node (this will most probably appear as 'Default Web Server'), and select 'Properties'.
If you want to install ruby-web as a CGI, do the following:
ruby-web.exe file.
An example value is: C:\ruby\bin\ruby-web.exe
Supply .rb or .rhtml as the extension.
Leave 'Method exclusions' blank, and check the 'Script engine' checkbox.
Now, click OK a few times.
c:\ruby\bin
and read rights for I_USR_ to the c:\ruby\lib directories.
In order to use index.rhtml as a default content page,
do the following: From within the Documents tab, choose Add. Type in
index.rhtml and click OK. Adjust the order by choosing
Move Up or Move Down. This is similar to setting DirectoryIndex with
Apache.
This section contains notes and hints specific to Apache 1.3.x installs of ruby-web on Microsoft Windows systems. There are also instructions and notes for Apache 2 on a separate page.
Please read the manual installation steps first!
After changing the configuration file, remember to restart the server, for example, NET STOP APACHE followed by NET START APACHE, if you run Apache as a Windows Service, or use your regular shortcuts.
Remember that when adding
path values in the Apache configuration files on Windows, all backslashes
such as c:\directory\file.ext must be converted to
forward slashes, as c:/directory/file.ext.
If your ruby is installed in C:\ruby\ as described
in the Manual
Installation Steps section, you need to insert
these lines to your Apache configuration file to set
up the CGI binary:
Example 4.1. ruby-web and Apache 1.3.x as CGI
ScriptAlias /ruby/ "c:/ruby/bin"
AddType application/x-httpd-ruby .rb
Action application/x-httpd-rb "/ruby/ruby-web.exe"
Note that the second line in the list above can be found
in the actual versions of httpd.conf, but it is commented out. Remember
also to substitute the c:/ruby/ for your actual path to Ruby.
This section contains notes and hints specific to Apache 2.0.x installs of ruby-web on Microsoft Windows systems. We also have instructions and notes for Apache 1.3.x users on a separate page.
You should read the manual installation steps first!
You are highly encouraged to take a look at the Apache Documentation to get a basic understanding of the Apache 2.0.x Server. Also consider to read the Windows specific notes for Apache 2.0.x before reading on here.
Apache 2.0.x is designed to run on Windows NT 4.0, Windows 2000 or Windows XP. At this time, support for Windows 9x is incomplete. Apache 2.0.x is not expected to work on those platforms at this time.
Download the most recent version of Apache 2.0.x and a fitting ruby-web version. Follow the Manual Installation Steps and come back to go on with the integration of ruby-web and Apache.
Remember that when adding
path values in the Apache configuration files on Windows, all backslashes
such as c:\directory\file.ext must be converted to
forward slashes, as c:/directory/file.ext.
The simplest way to install ruby-web is to use the installer found in the ruby-web.x.x.x-powerpc-darwin.dmg. This will install ruby-web and configure the default Apache with mod_ruby.
The installer has been tested on Mac OS X Tiger (10.4). Please let me know (install.help@hexane.org) if you have success or failure on other versions of Mac OS X.
If the installer does not work on your version of Mac OS X, use the unix instructions to install and configure ruby-web by hand.
Table of Contents
If you are still stuck, someone on the ruby-web mailing list may be able to help you. To subscribe to the ruby-web installation mailing list, submit the form athttp://lists.sourceforge.net/lists/listinfo/narf-lib-devel. The mailing list address is narf-devel@sourceforge.net.
If you want to get help on the mailing list, please try to be precise and give the necessary details about your environment (which operating system, what ruby-web version, what web server, if you are running ruby-web as CGI or a server module, safe mode, etc...), and preferably enough code to make others able to reproduce and test your problem.
If you think you have found a bug in ruby-web, please report it. The ruby-web developers probably don't know about it, and unless you report it, chances are it won't be fixed. You can report bugs using the bug-tracking system at http://rubyforge.org/tracker/?group_id=873. Please do not send bug reports in mailing list or personal letters. The bug system is also suitable to submit feature requests.
Table of Contents
Templates can be loaded using Web::load(filename). ruby-web loads .rb files as ruby, and assumes everything else is an erb template. Below is a short guide to erb templating:
The ruby-web interpreter will open a connection to the webserver and load the first command-line argument using Web::load. In a script, one can include additional files using Web::load.
In a ruby script, one can also open a Web::Connection using Web::open. This is not recommended, but is documented here for use in unsupported server environments.
#!/usr/bin/ruby require 'web' Web::open do |connection| Web::write "Hello" cgi.write "World" end
Guide to options (defaults are in parenthesis):
Variables directly submitted by the client are parsed into hashes of { name => [ multiple, values ] } :
These hashes are merged together into Web::request, which also is a hash of { name => [ multiple, values ] }. Web[param] is a convenience method to return single values.
File uploads are parsed into Web::Upload objects, with the following methods:
Environment variables are copied into a case-insensitive, duck-typing hash (eg Web::env[:script_name])
# sends ".../ruby/site_lib/1.8/web/resources/logo.gif" to the client Web::send_lib_file( 'resources/logo.gif' )
Web::filter do |content| # ... filter content end
Web::status = 200
Sends client a cookie with the given name and a value, and these optional keyword arguments:
url_encoded_string = Web::escape("'Stop!' said Fred")
# => "%27Stop%21%27+said+Fred"
print Web::escape_element('<BR><A HREF="url"></A>', "A", "IMG")
# "<BR><A HREF="url"></A>"
print Web::escape_element('<BR><A HREF="url"></A>', ["A", "IMG"])
# "<BR><A HREF="url"></A>"
Web::escape_html('Usage: foo "bar" <baz>')
# => "Usage: foo "bar" <baz>"
template = Web::lib_file_contents('resources/template.html')
Web::lib_filename('resources/logo.gif')
# => ".../ruby/site_lib/1.8/web/resources/logo.gif"Web::rfc1123_date(Time.now) # => Sat, 01 Jan 2000 00:00:00 GMT
string = Web::unescape("%27Stop%21%27+said+Fred")
# => "'Stop!' said Fred"
print Web::unescape_element(
Web::escapeHTML('<BR><A HREF="url"></A>'), "A", "IMG")
# "<BR><A HREF="url"></A>"
print Web::unescape_element(
Web::escapeHTML('<BR><A HREF="url"></A>'), ["A", "IMG"])
# "<BR><A HREF="url"></A>"
Web::unescape_html("Usage: foo "bar" <baz>")
# => "Usage: foo \"bar\" <baz>"Config directives are set using Web::config[:directive] = value. If desired, config directives can be set within 'site_lib/x.x/web/site-config.rb'.
Below is a list of available config directives:
:load_suffix contains a hash of handlers for different file extensions. You can then control the behavior of Web::load:
Web::config[:load_suffix][:amrita] = lambda do |scriptname| #...handle amrita templates... end
:load_suffix by default will load .rb and .erb files appropriately. Everything else is loaded using ruby-web's default templating.
Table of Contents
ruby-web ships with the cgi.rb interface, adapted to use the ruby-web infrastructure.
require 'web/shim/cgi' cgi = CGI.new # ...
You can customize how ruby-web load templates:
require 'web/phprb'
Web::config['load_suffix']['rhtml'] = lambda do |scriptname|
PHPRB::load(scriptname)
end
# or, if you really really love your templating language:
Web::config['load_suffix'].default = lambda do |scriptname|
PHPRB::load(scriptname)
end
Web::load('template.rhtml') # <= will be processed by phprbphprb is an experimental template parser derived from erb, but not as inspired by the systems invented by Sun and Microsoft. It has the following rules:
To access these functions, include Web::Testing in your testcase
require 'web/testing' require 'web/unit/testcase' class MyWebTest << Test::Unit::TestCase include Web::Testing #... end
Do a mock request to scriptname, passing in params.
scriptname can be /absolute/scriptname.rb if you use set the docroot using Web::docroot = "...". Otherwise, use a relative path from the current directory.
params is a hash of request parameters. You can mock enviroment parameters on an :env key.
Table of Contents
ruby-web is written by Patrick May and Tom Clarke, partly based on cgi.rb written by Wakou Aoyama. It makes significant use of ruby-htmltools, written by Ned Konz. Also, Keunwoo Lee patched Request.read_multipart to be cleaner.
ruby-web contains code from the following projects, and we are in their debt:
Much of the installation portion of the manual has been derived from the PHP manual. Below are the many contributers to this great resource.
We highlight the currently most active people on the manual frontpage, but there are many more contributors who currently help in our work or provided a great amount of help to the project in the past. There are a lot of unnamed people who help out with their user notes on manual pages, which continually get included in the references, the work of whom we are also very thankful for. All the lists provided below are in alphabetical order.
The following contributors should be recognized for the impact they have made and/or continue to make by adding content to the manual: Jouni Ahto, Alexander Aulbach, Daniel Beckham, Stig Bakken, Jesus M. Castagnetto, Ron Chmara, Sean Coates, John Coggeshall, Simone Cortesi, Markus Fischer, Wez Furlong, Sara Golemon, Rui Hirokawa, Brad House, Moriyoshi Koizumi, Rasmus Lerdorf, Andrew Lindeman, Stanislav Malyshev, Rafael Martinez, Yasuo Ohgaki, Derick Rethans, Sander Roobol, Egon Schmid, Thomas Schoefbeck, Sascha Schumann, Dan Scott, Lars Torben Wilson, Jim Winstead, Jeroen van Wolffelaar and Andrei Zmievski.
The following contributors have done significant work editing the manual: Stig Bakken, Hartmut Holzgraefe and Egon Schmid.
The currently most active maintainers are: Mehdi Achour, Friedhelm Betz, Vincent Gevers, Aidan Lister, Nuno Lopes and Tom Sommer.
These people have also put a lot of effort into managing user notes: Daniel Beckham, Victor Boivie, Jesus M. Castagnetto, Nicolas Chaillan, Ron Chmara, James Cox, Sara Golemon, Zak Greant, Szabolcs Heilig, Oliver Hinckel, Hartmut Holzgraefe, Rasmus Lerdorf, Andrew Lindeman, Maxim Maletsky, James Moore, Sebastian Picklum, Derick Rethans, Sander Roobol, Damien Seguy, Jason Sheets, Jani Taskinen, Yasuo Ohgaki, Philip Olson, Lars Torben Wilson, Jim Winstead, Jared Wyles and Jeroen van Wolffelaar.