Hook system improvements

+ Allow assigning multiple hook types to a class.
+ Add hook types, that are executed (almost) on every occasion.
This commit is contained in:
magmaus3 2022-11-20 13:21:45 +01:00
parent d4b2efe048
commit e66ed05ef7
Signed by: magmaus3
GPG key ID: 966755D3F4A9B251
2 changed files with 23 additions and 23 deletions

View file

@ -11,21 +11,30 @@ class HookMan:
def __new__(cls): def __new__(cls):
return reduce(lambda x, y: y(x), cls.hooks, super(HookMan, cls).__new__(cls)) return reduce(lambda x, y: y(x), cls.hooks, super(HookMan, cls).__new__(cls))
def execute_hooks(self, hook_type, *args, **kwargs): def execute_hooks(self, hook_type, isAdminAction=False, *args, **kwargs):
if hook_type not in self.hooks: if hook_type not in self.hooks:
return hook_type = None
for hook in self.hooks[hook_type]: if isAdminAction:
print(f"Executing hook {hook.__name__}") admin_hooks = self.hooks["admin*"]
else:
admin_hooks = []
for hook in \
(lambda: self.hooks[hook_type] if hook_type in self.hooks else [])() \
+ (lambda: self.hooks["*"] if "*" in self.hooks else [])() \
+ admin_hooks:
print(f"\tExecuting hook {hook.__name__}")
try: try:
hook()(*args, **kwargs) hook()(hook_type=hook_type, isAdminAction=isAdminAction, *args, **kwargs)
except Exception as exc: except Exception as exc:
raise HookException(exc) raise HookException(exc)
@classmethod @classmethod
def add_hook(cls, func, *args, **kwargs): def add_hook(cls, func, *args, **kwargs):
"""Adds a hook.""" """Adds a hook."""
hook_type = func.hook_type hook_types = func.hook_type
for hook_type in hook_types:
if hook_type in cls.hooks: if hook_type in cls.hooks:
cls.hooks[hook_type] = cls.hooks[hook_type] + [func] cls.hooks[hook_type] = cls.hooks[hook_type] + [func]
else: else:
@ -34,13 +43,3 @@ class HookMan:
hook = HookMan() hook = HookMan()
# @hook.add_hook
# class example_hook:
# """Example hook."""
# hook_type = "player_login"
#
# def __call__(self, *args, **kwargs):
# print("Hook player_login,", kwargs)
#
#
hook.execute_hooks("player_login", hello="john")

View file

@ -11,8 +11,9 @@ hook = hook_system.hook
class Login: class Login:
# Different hook types are executed at different places. # Different hook types are executed at different places.
# In this case, the hook is executed when a user logs in. # In this case, the hook is executed when a user logs in.
#
# Check the documentation for more hook types. # Check the documentation for more hook types.
hook_type = "player_login" hook_type = ["player_login"]
def __call__(self, *args, **kwargs): def __call__(self, hook_type, *args, **kwargs):
print("LOGIN HOOK:", args, kwargs) print("LOGIN HOOK:", args, kwargs)