1#
2# erbhandler.rb -- ERBHandler Class
3#
4# Author: IPR -- Internet Programming with Ruby -- writers
5# Copyright (c) 2001 TAKAHASHI Masayoshi, GOTOU Yuuzou
6# Copyright (c) 2002 Internet Programming with Ruby writers. All rights
7# reserved.
8#
9# $IPR: erbhandler.rb,v 1.25 2003/02/24 19:25:31 gotoyuzo Exp $
10
11require 'webrick/httpservlet/abstract.rb'
12
13require 'erb'
14
15module WEBrick
16  module HTTPServlet
17
18    ##
19    # ERBHandler evaluates an ERB file and returns the result.  This handler
20    # is automatically used if there are .rhtml files in a directory served by
21    # the FileHandler.
22    #
23    # ERBHandler supports GET and POST methods.
24    #
25    # The ERB file is evaluated with the local variables +servlet_request+ and
26    # +servlet_response+ which are a WEBrick::HTTPRequest and
27    # WEBrick::HTTPResponse respectively.
28    #
29    # Example .rhtml file:
30    #
31    #   Request to <%= servlet_request.request_uri %>
32    #
33    #   Query params <%= servlet_request.query.inspect %>
34
35    class ERBHandler < AbstractServlet
36
37      ##
38      # Creates a new ERBHandler on +server+ that will evaluate and serve the
39      # ERB file +name+
40
41      def initialize(server, name)
42        super(server, name)
43        @script_filename = name
44      end
45
46      ##
47      # Handles GET requests
48
49      def do_GET(req, res)
50        unless defined?(ERB)
51          @logger.warn "#{self.class}: ERB not defined."
52          raise HTTPStatus::Forbidden, "ERBHandler cannot work."
53        end
54        begin
55          data = open(@script_filename){|io| io.read }
56          res.body = evaluate(ERB.new(data), req, res)
57          res['content-type'] ||=
58            HTTPUtils::mime_type(@script_filename, @config[:MimeTypes])
59        rescue StandardError => ex
60          raise
61        rescue Exception => ex
62          @logger.error(ex)
63          raise HTTPStatus::InternalServerError, ex.message
64        end
65      end
66
67      ##
68      # Handles POST requests
69
70      alias do_POST do_GET
71
72      private
73
74      ##
75      # Evaluates +erb+ providing +servlet_request+ and +servlet_response+ as
76      # local variables.
77
78      def evaluate(erb, servlet_request, servlet_response)
79        Module.new.module_eval{
80          servlet_request.meta_vars
81          servlet_request.query
82          erb.result(binding)
83        }
84      end
85    end
86  end
87end
88