Commit d42cc5e5 authored by Eliot Berriot's avatar Eliot Berriot

Added prepare_name hook for manipulating name before registration

parent 9762e67c
......@@ -23,7 +23,7 @@ class Registry(OrderedDict):
def register(self, obj=None, name=None, **kwargs):
"""
Use this method as a decorator on class/funciton you want to register:
Use this method as a decorator on class/function you want to register:
@registry.register(name="test")
class Test:
......@@ -60,23 +60,31 @@ class Registry(OrderedDict):
"""
return True
def prepare_name(self, obj, name=None):
if name is None:
return self.get_object_name(obj)
return name
def register_func(self, obj, name=None, **kwargs):
"""
Register an object, class, function... into the registry
"""
if self.validate(obj):
if name is None:
name = self.get_object_name(obj)
self[name] = self.prepare_data(obj)
o = self.prepare_data(obj)
n = self.prepare_name(obj, name)
self[n] = o
else:
raise ValueError("{0} (type: {0.__class__}) is not a valid value for {1} registry".format(obj, self.__class__))
def prepare_data(self, obj):
"""
Override this methode if you want to manipulate data before registering it
You MUST return a value to register
"""
return obj
def autodiscover(self, apps, force_reload=True):
"""
Iterate throught every installed apps, trying to import `look_into` package
......
......@@ -124,5 +124,24 @@ class RegistryTest(unittest.TestCase):
self.assertEqual(r.get('eliot'), "hello eliot")
self.assertEqual(r.get('roger'), "hello roger")
def test_can_manipulate_key_before_registering(self):
class ModifyKey(registries.Registry):
def prepare_name(self, obj, key=None):
return "custom_key " + obj.name
r = ModifyKey()
class N:
def __init__(self, name):
self.name = name
n1 = N(name="eliot")
n2 = N(name="alain")
r.register(n1)
r.register(n2)
self.assertEqual(r.get('custom_key eliot'), n1)
self.assertEqual(r.get('custom_key alain'), n2)
if __name__ == '__main__':
unittest.main()
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment