Merge pull request #154 from gazpachoking/validate_hooks

Cause an error when trying to hook invalid HookMixin method
This commit is contained in:
Chase Sterling 2016-07-13 21:08:40 -04:00 committed by GitHub
commit 7a7dfd5097

View file

@ -25,9 +25,15 @@ class HookMixinMeta(type):
def __new__(cls, name, bases, attrs): def __new__(cls, name, bases, attrs):
super_new = super(HookMixinMeta, cls).__new__ super_new = super(HookMixinMeta, cls).__new__
hookable = []
for key, value in attrs.items(): for key, value in attrs.items():
# Disallow hooking methods which start with an underscore (allow __init__ etc. still)
if key.startswith('_') and not key.startswith('__'):
continue
if callable(value): if callable(value):
attrs[key] = hook_func(key, value) attrs[key] = hook_func(key, value)
hookable.append(key)
attrs['_hookable'] = hookable
return super_new(cls, name, bases, attrs) return super_new(cls, name, bases, attrs)
@ -37,9 +43,12 @@ class HookMixin(object):
_pre_hooks = {} _pre_hooks = {}
_post_hooks = {} _post_hooks = {}
_hookable = []
@classmethod @classmethod
def after(cls, method_name): def after(cls, method_name):
assert method_name in cls._hookable, "'%s' not a hookable method of '%s'" % (method_name, cls.__name__)
def outer(f, *args, **kwargs): def outer(f, *args, **kwargs):
cls._post_hooks.setdefault(method_name, []).append((f, args, kwargs)) cls._post_hooks.setdefault(method_name, []).append((f, args, kwargs))
return f return f
@ -47,6 +56,8 @@ class HookMixin(object):
@classmethod @classmethod
def before(cls, method_name): def before(cls, method_name):
assert method_name in cls._hookable, "'%s' not a hookable method of '%s'" % (method_name, cls.__name__)
def outer(f, *args, **kwargs): def outer(f, *args, **kwargs):
cls._pre_hooks.setdefault(method_name, []).append((f, args, kwargs)) cls._pre_hooks.setdefault(method_name, []).append((f, args, kwargs))
return f return f