Module dispatch_compiler

Compile dispatch rules to an Erlang module.

Copyright © 2015 Marc Worrell

Authors: Marc Worrell (marc@worrell.nl).

Description

Compile dispatch rules to an Erlang module.

The dispatch compiler takes all the list of dispatch rules and creates an Erlang module that matches those rules.

The Erlang module exports a single function: match/2.

This function takes the binary request path, split on "/" and return the matched dispatch rule and list of bindings.

The dispatch function looks like:

  match([], Context) ->
       {ok, {{home, [], controller_page, [...]}, []}};
  match([<<"page">>, Id, Slug], Context) ->
       {ok, {{page, ["page", id, slug], controller_page, [...]}, [{id,Id}, {slug,Slug}]}};
  match([<<"lib">> | Star], Context) when Star =/= [] ->
       {ok, {{lib, ["lib", '*'], controller_file, [...]}, [{'*',Star}]}};
  match(_, _Context) ->
       fail.

Rules can also have conditions on their arguments. The condition are matched using the runtime dispatch_compiler:bind/3 function.

  match([<<"id">>, Foo] = Path, Context) ->
       case dispatch_compiler:runtime_bind(Path, ["id", id], Context) of
           {ok, Bindings} ->
               {ok, {{id, ["id", id], controller_id, [...]}, Bindings}};
           fail ->
               match1(Path, Context)
       end;
  match(Path, Context) ->
       match1(Path, Context).
 
  match1(..., Context) ->
       ...
  match1(_, _Context) ->
       fail.

Data Types

binding()

binding() = {atom(), binary() | [binary() | any()]}

dispatch_rule()

dispatch_rule() = {Name::atom(), dispatch_rule_path(), Handler::any(), HandlerArgs::list()}

dispatch_rule_path()

dispatch_rule_path() = [dispatch_rule_token()]

dispatch_rule_token()

dispatch_rule_token() = binary() | '*' | atom() | {atom(), {atom(), atom()}} | {atom(), {atom(), atom(), list()}} | {atom(), match_function()} | {atom(), RegExp::iodata() | unicode:charlist()} | {atom(), RegExp::iodata() | unicode:charlist(), Options::list()}

match_function()

match_function() = fun((binary(), any()) -> boolean() | {ok, any()}) | fun((binary()) -> boolean() | {ok, any()})

Function Index

compile/2Compile Erlang module.
compile_load/2Compile and load Erlang module.
match/3Launch Module match function.
runtime_bind/3Runtime callback for argument binding with checks on the arguments.

Function Details

compile/2

compile(ModuleName::atom(), DLs::[dispatch_rule()]) -> {ok, atom(), binary()}

Compile Erlang module.

compile_load/2

compile_load(ModuleName, DLs) -> Result

Compile and load Erlang module.

match/3

match(Module, Tokens, Context) -> Result

Equivalent to Module:match(Tokens, Context).

Launch Module match function.

runtime_bind/3

runtime_bind(Pattern, Path, Context) -> Result

Runtime callback for argument binding with checks on the arguments. The checks can be a function, module-function, or regexp.


Generated by EDoc