Skip to content

Instantly share code, notes, and snippets.

@mokevnin
Created Dec 23, 2013
Embed
What would you like to do?
naming routes for cowboy
-module(routes).
-export([compile/0, generate_path/2, generate_url/3]).
compile() ->
List = [root, games, game, start_game],
cowboy_router:compile([
%% {URIHost, list({URIPath, Handler, Opts})}
{'_', [route(Name) || Name <- List]}
]).
route(root) ->
{"/", welcome_handler, []};
route(games) ->
{"/games", bullet_handler, [{handler, games_handler}]};
route(game) ->
{"/games/:id", bullet_handler, [{handler, game_handler}]};
route(start_game) ->
{"/games/:id/start", start_game_handler, []}.
generate_path(RouteName, Bindings) ->
Path = element(1, route(RouteName)),
GeneratedPath = lists:foldl(fun({Key, Value}, Acc) ->
re:replace(Acc, [":" | atom_to_list(Key)], to_string(Value), [global, {return, list}]) end, Path, Bindings),
list_to_binary(GeneratedPath).
generate_url(RouteName, Bindings, Host) ->
Path = generate_path(RouteName, Bindings),
<<"http://", Host/binary, Path/binary>>.
to_string(Value) when is_atom(Value) ->
atom_to_list(Value);
to_string(Value) when is_integer(Value) ->
integer_to_list(Value);
to_string(Value) when is_binary(Value) ->
binary_to_list(Value).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment