Class: Butler::Handler

Inherits:
Object
  • Object
show all
Defined in:
lib/butler/handler.rb

Overview

Butler::Handler

The link between Butler::Static and Butler::Asset Transforms HTTP header rules into actual HTTP headers for a single file to be set by Butler::Asset

Code adapted from Rails’ ActionDispatch::FileHandler

Instance Method Summary collapse

Constructor Details

#initialize(root, options = {}) ⇒ Handler

Returns a new instance of Handler.



16
17
18
19
20
21
22
# File 'lib/butler/handler.rb', line 16

def initialize(root, options={})
  @root          = root.chomp('/')
  @compiled_root = /^#{Regexp.escape(root)}/
  @headers       = {}
  @header_rules  = options[:header_rules] || {}
  @file_server   = Butler::Asset.new(@root, headers: @headers)
end

Instance Method Details

#call(env) ⇒ Object



39
40
41
42
43
# File 'lib/butler/handler.rb', line 39

def call(env)
  @path = env['PATH_INFO']
  set_headers
  @file_server.call(env)
end

#escape_glob_chars(path) ⇒ Object



56
57
58
59
# File 'lib/butler/handler.rb', line 56

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

#extObject



45
46
47
48
49
50
# File 'lib/butler/handler.rb', line 45

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

#match?(path) ⇒ Boolean

Returns:

  • (Boolean)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/butler/handler.rb', line 24

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]
  match = matches.detect { |m| File.file?(m) }
  if match
    match.sub!(@compiled_root, '')
    ::Rack::Utils.escape(match)
  end
end

#set_header(result) ⇒ Object



85
86
87
88
89
# File 'lib/butler/handler.rb', line 85

def set_header(result)
  result.each do |field, content|
    @headers[field] = content
  end
end

#set_headersObject

Convert header rules to headers



62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
# File 'lib/butler/handler.rb', line 62

def set_headers
  @header_rules.each do |rule, result|
    case rule
    when :global
      set_header(result)
    when :fonts
      set_header(result) if @path.match(%r{\.(?:ttf|otf|eot|woff|svg)\z})
    when Regexp
      set_header(result) if @path.match(rule)
    when Array
      # Extensions
      extensions = rule.join('|')
      set_header(result) if @path.match(%r{\.(#{extensions})\z})
    when String
      # Folder
      path = ::Rack::Utils.unescape(@path)
      set_header(result) if
        (path.start_with?(rule) || path.start_with?('/' + rule))
    else
    end
  end
end

#unescape_path(path) ⇒ Object



52
53
54
# File 'lib/butler/handler.rb', line 52

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