lib/pdfkit/middleware.rb in pdfkit-0.6.2 vs lib/pdfkit/middleware.rb in pdfkit-0.7.0

- old
+ new

@@ -1,13 +1,12 @@ class PDFKit - class Middleware - def initialize(app, options = {}, conditions = {}) @app = app @options = options @conditions = conditions + @render_pdf = false end def call(env) @request = Rack::Request.new(env) @render_pdf = false @@ -40,42 +39,43 @@ [status, headers, response] end private - # Change relative paths to absolute + # Change relative paths to absolute, and relative protocols to absolute protocols def translate_paths(body, env) - # Host with protocol + body = translate_relative_paths(body, env) + translate_relative_protocols(body, env) + end + + def translate_relative_paths(body, env) root = PDFKit.configuration.root_url || "#{env['rack.url_scheme']}://#{env['HTTP_HOST']}/" + # Try out this regexp using rubular http://rubular.com/r/vmuGSkheuu + body.gsub(/(href|src)=(['"])\/([^\/]([^\"']*|[^"']*))['"]/, "\\1=\\2#{root}\\3\\2") + end - body.gsub(/(href|src)=(['"])\/([^\/]([^\"']*|[^"']*))['"]/, '\1=\2' + root + '\3\2') + def translate_relative_protocols(body, env) + protocol = "#{env['rack.url_scheme']}://" + # Try out this regexp using rubular http://rubular.com/r/0Ohk0wFYxV + body.gsub(/(href|src)=(['"])\/\/([^\"']*|[^"']*)['"]/, "\\1=\\2#{protocol}\\3\\2") end def rendering_pdf? @render_pdf end def render_as_pdf? - request_path_is_pdf = @request.path.match(%r{\.pdf$}) + request_path = @request.path + request_path_is_pdf = request_path.match(%r{\.pdf$}) if request_path_is_pdf && @conditions[:only] - rules = [@conditions[:only]].flatten - rules.any? do |pattern| - if pattern.is_a?(Regexp) - @request.path =~ pattern - else - @request.path[0, pattern.length] == pattern - end + conditions_as_regexp(@conditions[:only]).any? do |pattern| + request_path =~ pattern end elsif request_path_is_pdf && @conditions[:except] - rules = [@conditions[:except]].flatten - rules.map do |pattern| - if pattern.is_a?(Regexp) - return false if @request.path =~ pattern - else - return false if @request.path[0, pattern.length] == pattern - end + conditions_as_regexp(@conditions[:except]).each do |pattern| + return false if request_path =~ pattern end return true else request_path_is_pdf @@ -96,7 +96,12 @@ def concat(accepts, type) (accepts || '').split(',').unshift(type).compact.join(',') end + def conditions_as_regexp(conditions) + [conditions].flatten.map do |pattern| + pattern.is_a?(Regexp) ? pattern : Regexp.new('^' + pattern) + end + end end end