Source code for superdjango.interfaces.hooks.library

# Imports

from operator import itemgetter
from superdjango.shortcuts import get_app_modules

# Exports

__all__ = (
    "HookManager",
)

# Classes


[docs]class HookManager(object): """Serves as registry and interface for hooks."""
[docs] def __init__(self, module_name="hooks"): """Initialize the hook manager. :param module_name: The name of the module to look for hooks. :type module_name: """ self.hooks = dict() self.is_loaded = False self.module_name = module_name
[docs] def get(self, name): """An alias for ``get_hooks()``.""" return self.get_hooks(name)
[docs] def get_hooks(self, name): """Get the hooks defined for the named hook. :param name: The name of the hook. :type name: str :rtype: list :returns: A list of hooks (callables) for the given name. """ self.load() _hooks = self.hooks.get(name, list()) _hooks = sorted(_hooks, key=itemgetter(1)) return [hook[0] for hook in _hooks]
[docs] def load(self): """Load hook modules if not already loaded.""" if not self.is_loaded: list(get_app_modules(self.module_name)) self.is_loaded = True
[docs] def register(self, function, hook=None, sort_order=0): """Register a function as a hook. :param function: The function to call for the hook. :param hook: The name of the hook. Defaults to the name of the function. :type hook: str :param sort_order: The order in which the function should be called. :type sort_order: int """ if hook is None: hook = function.__name__ if hook not in self.hooks: self.hooks[hook] = list() self.hooks[hook].append((function, sort_order))