Class: PDFKit::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/pdfkit/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ Middleware

Returns a new instance of Middleware.



5
6
7
8
# File 'lib/pdfkit/middleware.rb', line 5

def initialize(app, options = {})
  @app = app
  @options = options
end

Instance Method Details

#call(env) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/pdfkit/middleware.rb', line 10

def call(env)
  @render_pdf = false
  set_request_to_render_as_pdf(env) if env['PATH_INFO'].match(/\.pdf$/)
  
  status, headers, response = @app.call(env)
  
  request = Rack::Request.new(env)
  if @render_pdf && headers['Content-Type'] =~ /text\/html|application\/xhtml\+xml/
    body = response.body
    
    body = translate_paths(body, env)
    
    pdf = PDFKit.new(body, @options)
    body = pdf.to_pdf
    
    # Do not cache PDFs
    puts "DELETING CACHING"
    headers.delete('ETag')
    headers.delete('Cache-Control')
    
    headers["Content-Length"] = body.bytes.to_a.size.to_s
    headers["Content-Type"] = "application/pdf"
    
    response = [body]
  end
  
  [status, headers, response]
end