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: Lookup, Node

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, lookup = nil) ⇒ EsiForRack

Returns a new instance of EsiForRack.



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

def initialize(app, lookup = nil)
  @app = app
  @lookup = lookup
end

Class Method Details

.response_body_to_str(response_body) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/esi_for_rack.rb', line 18

def self.response_body_to_str(response_body)
  if response_body.respond_to? :to_str
    response_body.to_str
  elsif response_body.respond_to?(:each)
    body = ''
    response_body.each { |part|
      body << part.to_s
    }
    body
  else
    raise TypeError, "stringable or iterable required"
  end
end

Instance Method Details

#call(env) ⇒ Object



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
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/esi_for_rack.rb', line 32

def call(env)
  @lookup ||= [Lookup::PassThrough.new(@app, env), Lookup::Http.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 = EsiForRack.response_body_to_str(result.last)) && body.index('<esi:')
    user_agent_hash = {}
    begin
      user_agent = SOC::SpyVsSpy.new(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.version.major, user_agent.version.minor].compact.join('.')
      
      user_agent_hash['os'] = if user_agent.os.windows?
        'WIN'
      elsif user_agent.os.osx?
        'MAC'
      else
        'OTHER'
      end
    rescue
      # error parsing ua
    end
    
    binding = {
      :HTTP_ACCEPT_LANGUAGE => Set.new((env['HTTP_ACCEPT_LANGUAGE'] || '').split(',').map{|l| l.gsub(/q=[0-9]\.[0-9]{1,3}/, '').gsub(';','').strip}),
      :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)
    
    parsed_body = context.parse(body).to_s
    response.header['Content-Length'] = parsed_body.size.to_s
    
    [response.status, response.headers, [parsed_body]]
  else
    result
  end
  
end