Class: Shrimp::Middleware

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

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Middleware



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

def initialize(app, options = { }, conditions = { })
  @app                        = app
  @options                    = options
  @conditions                 = conditions
  @options[:polling_interval] ||= 1
  @options[:polling_offset]   ||= 1
  @options[:cache_ttl]        ||= 1
  @options[:request_timeout]  ||= @options[:polling_interval] * 10
end

Instance Method Details

#call(env) ⇒ Object



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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/shrimp/middleware.rb', line 13

def call(env)
  @request = Rack::Request.new(env)
  if render_as_pdf? #&& headers['Content-Type'] =~ /text\/html|application\/xhtml\+xml/
    if already_rendered? && (up_to_date?(@options[:cache_ttl]) || @options[:cache_ttl] == 0)
      if File.size(render_to) == 0
        File.delete(render_to)
        remove_rendering_flag
        return error_response
      end
      return ready_response if env['HTTP_X_REQUESTED_WITH']
      file = File.open(render_to, "rb")
      body = file.read
      file.close
      File.delete(render_to) if @options[:cache_ttl] == 0
      remove_rendering_flag
      response                  = [body]
      headers                   = { }
      headers["Content-Length"] = (body.respond_to?(:bytesize) ? body.bytesize : body.size).to_s
      headers["Content-Type"]   = "application/pdf"
      [200, headers, response]
    else
      if rendering_in_progress?
        if rendering_timed_out?
          remove_rendering_flag
          error_response
        else
          reload_response(@options[:polling_interval])
        end
      else
        File.delete(render_to) if already_rendered?
        set_rendering_flag
        fire_phantom
        reload_response(@options[:polling_offset])
      end
    end
  else
    @app.call(env)
  end
end