Sha256: f676ce643dd47f82c29625fd577ee1c7a9f9b2ccd43e123794ef5f717b413215

Contents?: true

Size: 1.18 KB

Versions: 5

Compression:

Stored size: 1.18 KB

Contents

module Kontrol

  class Router

    def initialize
      @routing = []      
    end

    def map(pattern, block, options = {})
      @routing << [pattern, block, options]
    end

    OPTION_MAPPING = {
      :method => 'REQUEST_METHOD',
      :port => 'SERVER_PORT',
      :host => 'HTTP_HOST',
      :accept => 'HTTP_ACCEPT',
      :query => 'QUERY_STRING',
      :content_type => 'CONTENT_TYPE'      
    }

    def options_match(env, options)      
      options.all? do |name, pattern| 
        value = env[OPTION_MAPPING[name] || name]
        value and pattern.match(value)
      end
    end

    def call(env)
      path = env["PATH_INFO"].to_s.squeeze("/")      

      @routing.each do |pattern, app, options|        
        if (match = path.match(/^#{pattern}/)) && options_match(env, options)
          env = env.dup
          (env['kontrol.args'] ||= []).concat(match.to_a[1..-1])
          if match[0] == pattern
            env["SCRIPT_NAME"] += match[0]
            env["PATH_INFO"] = path[match[0].size..-1]
          end          
          return app.call(env)
        end
      end

      [404, {"Content-Type" => "text/plain"}, ["Not Found: #{env['REQUEST_URI']}"]]
    end

  end

end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
georgi-kontrol-0.1.2 lib/kontrol/router.rb
georgi-kontrol-0.1.3 lib/kontrol/router.rb
georgi-kontrol-0.1.4 lib/kontrol/router.rb
georgi-kontrol-0.1.5 lib/kontrol/router.rb
georgi-kontrol-0.1.6 lib/kontrol/router.rb