Class: EsiForRack

Inherits:
Object
  • Object
show all
Defined in:
lib/esi_for_rack.rb,
lib/esi_for_rack/node.rb,
lib/esi_for_rack/lookup.rb

Defined Under Namespace

Classes: IOWrapper, Lookup, Node

Instance Method Summary collapse

Constructor Details

#initialize(app, lookup = nil) ⇒ EsiForRack

Returns a new instance of EsiForRack.



12
13
14
15
# File 'lib/esi_for_rack.rb', line 12

def initialize(app, lookup = nil)
  @app = app
  @lookup = lookup
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
63
64
65
66
67
# File 'lib/esi_for_rack.rb', line 17

def call(env)
  @lookup ||= Lookup::PassThrough.new(@app, env)
  
  request = Rack::Request.new(env)
  result = @app.call(env)
  response = Rack::Response.new(result[2], result[0], result[1])

  if response['Content-Type'] =~ /text\/html/
    body = ""
    response.body.each do |part|
      body << part
    end
    
    user_agent_hash = {}
    begin
      user_agent = ParseUserAgent.new.parse(env['HTTP_USER_AGENT'] || '-')
      user_agent_hash['browser'] = case user_agent.browser
      when  'Firefox' then 'MOZILLA'
      when  'MSIE'    then 'MSIE'
      else;                'OTHER'
      end

      user_agent_hash['version'] = user_agent.browser_version_major

      user_agent_hash['os'] = case user_agent.ostype
      when  'Windows'   then 'WIN'
      when  'Macintosh' then 'MAC'
      else;                  'OTHER'
      end

    rescue
      # error parsing ua
    end
    
    
    
    binding = {
      :HTTP_ACCEPT_LANGUAGE => Set.new((env['HTTP_ACCEPT_LANGUAGE'] || '').split(',').map{|l| l.strip.gsub(/q=[0-9]\.[0-9]{1,3}/, '').gsub(';','')}),
      :HTTP_COOKIE => request.cookies,
      :HTTP_HOST => request.host,
      :HTTP_REFERER => request.referer,
      :HTTP_USER_AGENT => user_agent_hash,
      :QUERY_STRING => request.GET
    }
    context = Node::Context.new(binding, @lookup)
    [response.status, response.headers, [context.parse(body).to_s]]
  else
    result
  end
  
end