Class: Hx::Rack::Application

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input, options) ⇒ Application

Returns a new instance of Application.



37
38
39
40
# File 'lib/hx/rack/application.rb', line 37

def initialize(input, options)
  @input = input
  @index_names = Array(options[:index_names] || ['index.html'])
end

Class Method Details

.load_file(config_path) ⇒ Object



32
33
34
35
# File 'lib/hx/rack/application.rb', line 32

def self.load_file(config_path)
  site = Hx::Site.load_file(config_path)
  new(site, site.options)
end

Instance Method Details

#_call(env) ⇒ Object



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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/hx/rack/application.rb', line 46

def _call(env)
  request_method = env["REQUEST_METHOD"]

  if request_method != "GET" and request_method != "HEAD"
    return [405, {'Content-Type' => 'text/plain',
                  'Allow' => "GET, HEAD"},
            ["405 Method Not Allowed"]]
  end

  path = CGI.unescape(env['PATH_INFO'])
  path = '/' if path.empty?
  entry = nil

  has_trailing_slash = (path[-1..-1] == '/')

  # for non-slash-terminated paths, try the path directly
  unless has_trailing_slash
    begin
      effective_path = path[1..-1]
      entry = @input.get_entry(effective_path)
    rescue NoSuchEntryError
    end
  end

  # no entry? maybe it's a directory; look for an index entry
  unless entry
    path =~ %r(^/(.*?)/?$)
    prefix = $1
    prefix = "#{prefix}/" unless prefix.empty?
    for index_name in @index_names
      begin
        effective_path = "#{prefix}#{index_name}"
        entry = @input.get_entry(effective_path)
        break
      rescue NoSuchEntryError
      end
    end

    # directory exists, but missing trailing slash?
    if entry and not has_trailing_slash
      return [301, {'Content-Type' => 'text/plain',
                    'Location' => "#{env['SCRIPT_NAME']}#{path}/"},
              ["301 Moved Permanently"]]
    end
  end

  if entry
    content_type = entry['content_type'] 
    unless content_type
      effective_path =~ /(\.[^.]+)$/
      content_type = ::Rack::Mime.mime_type($1 || '')
    end
    if request_method != "HEAD"
      content = [entry['content'].to_s]
    else
      content = []
    end
    [200, {'Content-Type' => content_type}, content]
  else
    message = "#{env['SCRIPT_NAME']}#{path} not found"
    [404, {'Content-Type' => "text/plain"}, [message]]
  end
end

#call(env) ⇒ Object



42
43
44
# File 'lib/hx/rack/application.rb', line 42

def call(env)
  Hx.cache_scope { _call(env) }
end