Permalink
Browse files

Merge branch 'bz1293-remove-resource-with-predicate'

  • Loading branch information...
2 parents 9c39367 + 766ed32 commit 60d529c8bfa684d4f7cf95f465e3c023f1fe9468 Bryan Fink committed Aug 24, 2012
Showing with 32 additions and 10 deletions.
  1. +32 −10 src/webmachine_router.erl
View
@@ -99,8 +99,7 @@ init([]) ->
%% @private
handle_call({remove_resource, Resource}, _From, State) ->
- DL = [D || D <- get_dispatch_list(),
- filter_by_resource(D, Resource)],
+ DL = filter_by_resource(Resource, get_dispatch_list()),
{reply, set_dispatch_list(DL), State};
handle_call(get_routes, _From, State) ->
@@ -137,14 +136,21 @@ code_change(_OldVsn, State, _Extra) ->
{ok, State}.
%% Internal functions
-filter_by_resource({_, {_, Resource, _}}, Resource) ->
- false;
-filter_by_resource({_, {_, _, _}}, _Resource) ->
- true;
-filter_by_resource({_, Resource, _}, Resource) ->
- false;
-filter_by_resource({_, _, _}, _Resource) ->
- true.
+
+%% @doc Remove any dispatch rule that directs requests to `Resource'
+filter_by_resource(Resource, Dispatch) ->
+ lists:foldr(filter_by_resource(Resource), [], Dispatch).
+
+filter_by_resource(Resource) ->
+ fun({_, R, _}, Acc) when R == Resource -> % basic dispatch
+ Acc;
+ ({_, _, R, _}, Acc) when R == Resource -> % guarded dispatch
+ Acc;
+ ({Host, Disp}, Acc) -> % host-based dispatch
+ [{Host, filter_by_resource(Resource, Disp)}|Acc];
+ (Other, Acc) -> % dispatch not mentioning this resource
+ [Other|Acc]
+ end.
get_dispatch_list() ->
case application:get_env(webmachine, dispatch_list) of
@@ -184,11 +190,27 @@ add_remove_resource_test() ->
PathSpec1 = {["foo"], foo, []},
PathSpec2 = {["bar"], foo, []},
PathSpec3 = {["baz"], bar, []},
+ PathSpec4 = {["foo"], fun(_) -> true end, foo, []},
+ PathSpec5 = {["foo"], {webmachine_router, test_guard}, foo, []},
webmachine_router:add_route(PathSpec1),
webmachine_router:add_route(PathSpec2),
webmachine_router:add_route(PathSpec3),
webmachine_router:remove_resource(foo),
[PathSpec3] = get_routes(),
+ webmachine_router:add_route(PathSpec4),
+ webmachine_router:remove_resource(foo),
+ [PathSpec3] = get_routes(),
+ webmachine_router:add_route(PathSpec5),
+ webmachine_router:remove_resource(foo),
+ [PathSpec3] = get_routes(),
+ webmachine_router:remove_route(PathSpec3),
+ [begin
+ PathSpec = {"localhost", [HostPath]},
+ webmachine_router:add_route(PathSpec),
+ webmachine_router:remove_resource(foo),
+ [{"localhost", []}] = get_routes(),
+ webmachine_router:remove_route({"localhost", []})
+ end || HostPath <- [PathSpec1, PathSpec4, PathSpec5]],
exit(Pid, kill).
no_dupe_path_test() ->

0 comments on commit 60d529c

Please sign in to comment.