Class: Rack::PageSpeed

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/pagespeed.rb

Defined Under Namespace

Modules: Filters, Store Classes: Config

Constant Summary collapse

Filter =

shortcut

Base

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options, &block) ⇒ PageSpeed

Returns a new instance of PageSpeed.



10
11
12
13
# File 'lib/rack/pagespeed.rb', line 10

def initialize app, options, &block
  @app = app
  @config = Config.new options, &block
end

Instance Attribute Details

#configObject (readonly)

Returns the value of attribute config.



6
7
8
# File 'lib/rack/pagespeed.rb', line 6

def config
  @config
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/rack/pagespeed.rb', line 15

def call env
  if match = %r(^/rack-pagespeed-(.*)).match(env['PATH_INFO'])
    respond_with match[1]
  else
    status, headers, @response = @app.call(env)
    return [status, headers, @response] unless headers['Content-Type'] =~ /html/
    body = ""; @response.each do |part| body << part end
    @document = Nokogiri::HTML(body)
    @config.filters.each do |filter|
      filter.execute! @document
    end
    body = @document.to_html
    headers['Content-Length'] = body.length.to_s if headers['Content-Length'] # still UTF-8 unsafe
    [status, headers, [body]]        
  end
end

#respond_with(asset_id) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/rack/pagespeed.rb', line 32

def respond_with asset_id
  store = @config.store
  if asset = store[asset_id]
    [
      200,
      {
        'Content-Type' => (Rack::Mime.mime_type(::File.extname(asset_id))),
        'Cache-Control' => "public, max-age=#{(60*60*24*365.25*10).to_i}",
        'Expires' => (Time.now + 60*60*24*365.25*10).httpdate
      },
      [asset]
    ]
  else
    [404, {'Content-Type' => 'text/plain'}, ['Not found']]
  end
end