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
# 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)}/
  @file_server   = ::Rack::File.new(@root, cache_control)
end

Instance Method Details

#call(env) ⇒ Object



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

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



76
77
78
79
# File 'lib/action_dispatch/gz_static.rb', line 76

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

#extObject



64
65
66
67
68
69
70
# File 'lib/action_dispatch/gz_static.rb', line 64

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

#match?(path) ⇒ Boolean

Returns:

  • (Boolean)


18
19
20
21
22
23
24
25
26
# File 'lib/action_dispatch/gz_static.rb', line 18

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



72
73
74
# File 'lib/action_dispatch/gz_static.rb', line 72

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