Skip to content

Commit

Permalink
Merge pull request rails#11 from spohlenz/request_class_methods
Browse files Browse the repository at this point in the history
Find routes based on request class methods
  • Loading branch information
tenderlove committed Jan 13, 2012
2 parents 2c0889f + f1303e5 commit 9c956b8
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 7 deletions.
21 changes: 14 additions & 7 deletions lib/journey/router.rb
Expand Up @@ -29,6 +29,14 @@ def request_method
env['REQUEST_METHOD']
end

def path_info
env['PATH_INFO']
end

def ip
env['REMOTE_ADDR']
end

def [](k); env[k]; end
end

Expand Down Expand Up @@ -115,18 +123,17 @@ def filter_routes path
end

def find_routes env
addr = env['REMOTE_ADDR']
req = request_class.new env
req = request_class.new env

routes = filter_routes(env['PATH_INFO']) + custom_routes.find_all { |r|
r.path.match(env['PATH_INFO'])
routes = filter_routes(req.path_info) + custom_routes.find_all { |r|
r.path.match(req.path_info)
}

routes.sort_by(&:precedence).find_all { |r|
r.constraints.all? { |k,v| v === req.send(k) } &&
r.verb === env['REQUEST_METHOD']
}.reject { |r| addr && !(r.ip === addr) }.map { |r|
match_data = r.path.match(env['PATH_INFO'])
r.verb === req.request_method
}.reject { |r| req.ip && !(r.ip === req.ip) }.map { |r|
match_data = r.path.match(req.path_info)
match_names = match_data.names.map { |n| n.to_sym }
match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
info = Hash[match_names.zip(match_values).find_all { |_,y| y }]
Expand Down
28 changes: 28 additions & 0 deletions test/test_router.rb
Expand Up @@ -26,6 +26,10 @@ def hello
self.called = true
'world'
end

def path_info; env['PATH_INFO']; end
def request_method; env['REQUEST_METHOD']; end
def ip; env['REMOTE_ADDR']; end
end

def test_dashes
Expand Down Expand Up @@ -85,6 +89,30 @@ def test_request_class_and_requirements_fail
assert_equal env.env, klass.env
end

class CustomPathRequest < Router::NullReq
def path_info
env['custom.path_info']
end
end

def test_request_class_overrides_path_info
router = Router.new(routes, {:request_class => CustomPathRequest })

exp = Router::Strexp.new '/bar', {}, ['/.?']
path = Path::Pattern.new exp

routes.add_route nil, path, {}, {}, {}

env = rails_env 'PATH_INFO' => '/foo', 'custom.path_info' => '/bar'

recognized = false
router.recognize(env) do |r, _, params|
recognized = true
end

assert recognized, "route should have been recognized"
end

def test_regexp_first_precedence
add_routes @router, [
Router::Strexp.new("/whois/:domain", {:domain => /\w+\.[\w\.]+/}, ['/', '.', '?']),
Expand Down

0 comments on commit 9c956b8

Please sign in to comment.