Class: HerokuRailsDeflate::ServeZippedAssets

Inherits:
Object
  • Object
show all
Defined in:
lib/heroku_rails_deflate/serve_zipped_assets.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, root, asset_prefix, cache_control = nil) ⇒ ServeZippedAssets

Params:

root: the public directory
asset_prefix: config.assets.prefix
cache_control: config.static_cache_control


13
14
15
16
17
# File 'lib/heroku_rails_deflate/serve_zipped_assets.rb', line 13

def initialize(app, root, asset_prefix, cache_control=nil)
  @app = app
  @asset_prefix = asset_prefix.chomp('/') + '/'
  @file_handler = ActionDispatch::FileHandler.new(root, cache_control)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/heroku_rails_deflate/serve_zipped_assets.rb', line 19

def call(env)
  # Only process get requests
  if env['REQUEST_METHOD'] == 'GET'
    request = Rack::Request.new(env)

    # See if client accepts gzip encoding
    if Rack::Utils.select_best_encoding(%w(gzip identity), request.accept_encoding) == 'gzip'
      # Check if compressed version exists in assets directory
      compressed_path = env['PATH_INFO'] + '.gz'
      if compressed_path.start_with?(@asset_prefix) && (match = @file_handler.match?(compressed_path))
        # Use FileHandler to serve up the gzipped file, then strip the .gz suffix
        path = env["PATH_INFO"] = match
        status, headers, body = @file_handler.call(env)
        path = env["PATH_INFO"] = env["PATH_INFO"].chomp('.gz')

        # Set the Vary HTTP header.
        vary = headers["Vary"].to_s.split(",").map(&:strip)
        unless vary.include?("*") || vary.include?("Accept-Encoding")
          headers["Vary"] = vary.push("Accept-Encoding").join(",")
        end

        # Add encoding and type
        headers['Content-Encoding'] = 'gzip'
        headers['Content-Type'] = Rack::Mime.mime_type(File.extname(path), 'text/plain')

        # Update cache-control to add directive telling Rack::Deflate to leave it alone.
        cache_control = headers['Cache-Control'].try(:to_s).try(:downcase)
        if cache_control.nil?
          headers['Cache-Control'] = 'no-transform'
        elsif !cache_control.include?('no-transform')
          headers['Cache-Control'] += ', no-transform'
        end

        body.close if body.respond_to?(:close)
        return [status, headers, body]
      end
    end
  end

  @app.call(env)
end