class PhantomPDF::Middleware

Constants

REGEXP_PDF

Public Class Methods

new(app, output=nil) click to toggle source
# File lib/phantompdf/middleware.rb, line 5
def initialize(app, output=nil)
  @app = app
  @output = output
end

Public Instance Methods

call(env) click to toggle source
# File lib/phantompdf/middleware.rb, line 10
def call(env)
  @request = Rack::Request.new(env)

  return @app.call(env) unless request_pdf?

  status, headers, response = @app.call(env)
  return [status, headers, response] if status != 200 || headers['Content-Type'] != 'text/html'

  response_body = render_pdf(response.first)

  headers.merge!({
    'Content-Type' => 'application/pdf',
    'Content-Length' => response_body.size.to_s
  })

  [200, headers, [response_body]]
end

Private Instance Methods

render_path() click to toggle source
# File lib/phantompdf/middleware.rb, line 33
def render_path
  file_name = "#{Digest::MD5.hexdigest(@request.path)}.pdf"

  return Tempfile.new(file_name).path if @output.nil? || !File.directory?(@output) || !File.writable?(@output)

  "#{@output}/#{file_name}"
end
render_pdf(html) click to toggle source
# File lib/phantompdf/middleware.rb, line 29
def render_pdf(html)
  Generator.new(html, render_path).to_string
end
request_pdf?() click to toggle source
# File lib/phantompdf/middleware.rb, line 41
def request_pdf?
  return true if @request.path.match(Middleware::REGEXP_PDF)
  false
end