Section 6.2. Handlers

6.2. Handlers

Let's jump right into things and make a very simple handler that only reflects its parameters back to the Web browser. Put this code into a file named mongrel.conf:

class ParamDumper < Mongrel::HttpHandler   def process(req, resp)     resp.start do |head, body|       head['Content-Type'] = 'text/plain'       body.write(req.params.inspect)     end   end end uri "/dumped", :handler =>

Simple enough. We just say ParamDumper inherits HttpHandler, create a process method, and use the HttpResponse object to dump the HttpRequest#params variable via inspect. The last line actually calls Configurator#uri, but there's a bit of voodoo going on that we'll explain later. For now just understand that's how you attach a handler to a URI path. Notice also that we set the "Content-Type" to "text/plain" using the head variable.

Loading this for now will be as simple as:

mongrel_rails start -e production -S mongrel.conf

The -S option (which we first covered in Section 4) basically means "run this file as a configure script." A configure script is a Ruby script, but it is run within the context of an already configured Configurator object. This means that all the functions in Configurator like uri can be called as if they were global functions. The Configurator#uri function is the one you'll be calling the most.

When you get this running and it is working you should be able to go to http://localhost:3000/dumped with a browser and it'll spew the results to a text page. That's it, you've just written your first HttpHandler.

Mongrel. Serving, Deploying, and Extending Your Ruby Applications
Mongrel. Serving, Deploying, and Extending Your Ruby Applications
ISBN: 9812836357
Year: 2006
Pages: 48 © 2008-2017.
If you may any questions please contact us: