Class: TDiary::CGIAdapter

Inherits:
Object
  • Object
show all
Defined in:
lib/tdiary/cgi_adapter.rb

Overview

class CGIAdapter bridges CGI/FastCGI hosted requests to the Rack interface: builds a Rack env from a request and writes the Rack response triplet back to it. The request is duck-typed (env/in/out/err/finish) so that this file works without the fcgi gem.

Defined Under Namespace

Classes: PlainCGIRequest

Class Method Summary collapse

Class Method Details

.build_env(fcgi_env, input, errors) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tdiary/cgi_adapter.rb', line 33

def build_env( fcgi_env, input, errors )
	env = fcgi_env.to_hash.dup
	env.delete( 'HTTP_CONTENT_LENGTH' )
	env['SCRIPT_NAME'] = '' if env['SCRIPT_NAME'] == '/'
	env['QUERY_STRING'] ||= ''
	env['rack.input'] = StringIO.new( (input.read || '').b )
	env['rack.errors'] = errors
	env['rack.url_scheme'] = url_scheme( env )
	# tell Request#cgi_compat that js/theme are served statically
	# by the web server, not by the Rack app
	env['tdiary.static_assets'] = true
	env
end

.run(request, dispatcher) ⇒ Object



24
25
26
27
28
29
30
31
# File 'lib/tdiary/cgi_adapter.rb', line 24

def run( request, dispatcher )
	env = build_env( request.env.to_hash, request.in, request.err )
	write_response( request.out, *dispatcher.call( env ) )
rescue Exception => e
	write_error( request.out, e )
ensure
	request.finish
end

.run_cgi(dispatcher) ⇒ Object



19
20
21
22
# File 'lib/tdiary/cgi_adapter.rb', line 19

def run_cgi( dispatcher )
	$stdin.binmode
	run( PlainCGIRequest.new( ENV.to_hash, $stdin, $stdout, $stderr ), dispatcher )
end

.write_response(out, status, headers, body) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
# File 'lib/tdiary/cgi_adapter.rb', line 47

def write_response( out, status, headers, body )
	out.print "Status: #{status}\r\n"
	headers.each do |key, value|
		Array( value ).each do |v|
			v.to_s.split( "\n" ).each do |line|
				out.print "#{key}: #{line}\r\n"
			end
		end
	end
	out.print "\r\n"
	body.each {|part| out.print part }
ensure
	body.close if body.respond_to?( :close )
end