summaryrefslogtreecommitdiff
path: root/lib/chef_zero/router.rb
blob: 0389c8a5bc91344bed411d02d46a0b5785ff5c10 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
module ChefZero
  class Router
    def initialize(routes)
      @routes = routes.map do |route, endpoint|
        pattern = Regexp.new("^#{route.gsub('*', '[^/]*')}$")
        [ pattern, endpoint ]
      end
    end

    attr_reader :routes
    attr_accessor :not_found

    def call(env)
      puts "#{env['REQUEST_METHOD']} #{env['PATH_INFO']}#{env['QUERY_STRING'] != '' ? "?" + env['QUERY_STRING'] : ''}"
      clean_path = "/" + env['PATH_INFO'].split('/').select { |part| part != "" }.join("/")
      routes.each do |route, endpoint|
        if route.match(clean_path)
          return endpoint.call(env)
        end
      end
      not_found.call(env)
    end
  end
end