Skip to content

nomasystems/nhooks

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

11 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nhooks

Erlang hooks application. It allows adding tasks dynamically to predefined hooks.

Status

nhooks

Prerequisites

Min. OTP version Max. OTP version Min. rebar version

Configuration

In your rebar.config file, add the dependency:

{deps, [
    {nhooks, {git, "[email protected]:nomasystems/nhooks.git", {branch, "main"}}}
]}.

Usage example

Assuming there is a module named test_app that has one hook named init and another named terminate:

-module(test_app).

%%% EXTERNAL EXPORTS
-export([init/1, terminate/1]).

%%% NHOOKS EXPORTS
-export([hooks/0]).

%%%-----------------------------------------------------------------------------
%%% EXTERNAL EXPORTS
%%%-----------------------------------------------------------------------------
init(Term) ->
    nhooks:do(?MODULE, init, [Term]).

terminate(Term) ->
    nhooks:do(?MODULE, terminate, [Term]).

hooks() ->
    [
        init,
        terminate
    ].

You can register tasks to the defined hooks:

%%% Registering tasks in both hooks
ok = nhooks:register_task(test_app, init, fun(Term) ->
    do_something(Term)
end).

ok = nhooks:register_task(test_app, terminate, fun(Term) ->
    do_something_else(Term)
end).

From now on when test_app executes the init and terminate hooks the registered tasks will be executed.

You can also register multiple tasks to any defined hook:

%%% Registering multiple tasks to same hook
ok = nhooks:register_task(test_app, init, fun(Term) ->
    do_something(Term)
end).

ok = nhooks:register_task(test_app, init, fun(Term) ->
    do_something_else(Term)
end).

And all will be executed when test_app executes the init hook.

If you want to stop the subsequent tasks from executing, you can return stop or {stop, Data} from any task. For example:

%%% Stopping subsequent tasks in the same hook
ok = nhooks:register_task(test_app, init, fun(Term) ->
    do_something(Term),
    {stop, {some, data}}
end).

ok = nhooks:register_task(test_app, init, fun(Term) ->
    do_something_else(Term)
end).

In this case, the second task won't be executed and the call to nhooks:do/3 will return {stopped, {some, data}}.

All tasks are registered with a default priority of 0 and then executed from lowest to highest priority. That priority can be passed as the last argument of nhooks:register_task/4:

ok = nhooks:register_task(test_app, init, fun(_Term) -> first end, -1).
ok = nhooks:register_task(test_app, init, fun(_Term) -> second end).
ok = nhooks:register_task(test_app, init, fun(_Term) -> third end, 5).

Support

Any doubt or suggestion? Please check out our issue tracker.