Class: ActionDispatch::GzStatic

Inherits:
Object
  • Object
show all
Defined in:
lib/action_dispatch/gz_static.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, root, cache_control = nil) ⇒ GzStatic

Returns a new instance of GzStatic.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/action_dispatch/gz_static.rb', line 11

def initialize(app, root, cache_control=nil)
  @app           = app
  @root          = root.chomp('/')
  @compiled_root = /^#{Regexp.escape(@root)}/

  # I wish there was a better way to do this. Rack::File changed its
  # interface after 1.4.1 and I don't know of a way to sniff out the change
  # without comparing the gem version
  if Gem.loaded_specs['rack'].version > Gem::Version.new('1.4.1')
    cache_control = {'Cache-Control' => cache_control}
  end

  @file_server   = ::Rack::File.new(@root, cache_control)
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/action_dispatch/gz_static.rb', line 36

def call(env)
  case env['REQUEST_METHOD']
  when 'GET', 'HEAD'
    path = env['PATH_INFO'].chomp('/')
    if match = match?(path)

      compressed_match = "#{match}.gz"
      compressed_exists = File.file?(compressed_match)
        
      wants_compressed = !!(env['HTTP_ACCEPT_ENCODING'] =~ /\bgzip\b/)

      if wants_compressed && compressed_exists
        mime = Rack::Mime.mime_type(::File.extname(match), 'text/plain')
        match = compressed_match
      end

      match.sub!(@compiled_root, '')
      env["PATH_INFO"] = ::Rack::Utils.escape(match)
      status, headers, body = @file_server.call(env)

      if compressed_exists
        headers['Vary'] = 'Accept-Encoding'

        if wants_compressed
          headers['Content-Encoding'] = 'gzip'
          headers['Content-Type'] = mime if mime
        end
      end

      return [status, headers, body]
    end
  end

  @app.call(env)
end

#escape_glob_chars(path) ⇒ Object



84
85
86
87
# File 'lib/action_dispatch/gz_static.rb', line 84

def escape_glob_chars(path)
  path.force_encoding('binary') if path.respond_to? :force_encoding
  path.gsub(/[*?{}\[\]]/, "\\\\\\&")
end

#extObject



72
73
74
75
76
77
78
# File 'lib/action_dispatch/gz_static.rb', line 72

def ext
  @ext ||= begin
    #ext = ::ActionController::Base.default_static_extension
    ext = ".html"
    "{,#{ext},/index#{ext}}"
  end
end

#match?(path) ⇒ Boolean

Returns:

  • (Boolean)


26
27
28
29
30
31
32
33
34
# File 'lib/action_dispatch/gz_static.rb', line 26

def match?(path)
  path = path.dup

  full_path = path.empty? ? @root : File.join(@root, escape_glob_chars(unescape_path(path)))
  paths = "#{full_path}#{ext}"

  matches = Dir[paths]
  matches.detect { |m| File.file?(m) }
end

#unescape_path(path) ⇒ Object



80
81
82
# File 'lib/action_dispatch/gz_static.rb', line 80

def unescape_path(path)
  URI.parser.unescape(path)
end