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