Class: PDFKit::Middleware

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Middleware.



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

def initialize(app, options = {}, conditions = {})
  @app        = app
  @options    = options
  @conditions = conditions
  @render_pdf = false
  @caching    = @conditions.delete(:caching) { false }
end

Instance Method Details

#_call(env) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/pdfkit/middleware.rb', line 17

def _call(env)
  @request    = Rack::Request.new(env)
  @render_pdf = false

  set_request_to_render_as_pdf(env) if render_as_pdf?
  status, headers, response = @app.call(env)

  begin
    content_type_header = headers.has_key?('Content-Type') ? 'Content-Type' : 'content-type'
    if rendering_pdf? && headers[content_type_header] =~ /text\/html|application\/xhtml\+xml/
      body = response.respond_to?(:body) ? response.body : response.join
      body = body.join if body.is_a?(Array)

      root_url = root_url(env)
      protocol = protocol(env)
      options = @options.merge(root_url: root_url, protocol: protocol)

      if headers['PDFKit-javascript-delay']
        options.merge!(javascript_delay: headers.delete('PDFKit-javascript-delay').to_i)
      end

      body = PDFKit.new(body, options).to_pdf
      response = [body]

      if headers['PDFKit-save-pdf']
        File.open(headers['PDFKit-save-pdf'], 'wb') { |file| file.write(body) } rescue nil
        headers.delete('PDFKit-save-pdf')
      end

      unless @caching
        # Do not cache PDFs
        headers.delete('etag')
        headers.delete('cache-control')
      end

      headers['content-length'] = (body.respond_to?(:bytesize) ? body.bytesize : body.size).to_s
      headers[content_type_header]   = 'application/pdf'
      headers['content-disposition'] ||= @conditions[:disposition] || 'inline'
    end
  rescue StandardError => e
    status = 500
    response = [e.message]
  end

  [status, headers, response]
end

#call(env) ⇒ Object



13
14
15
# File 'lib/pdfkit/middleware.rb', line 13

def call(env)
  dup._call(env)
end