From 10a117ee884d4981b254674e69443ff2aadf384b Mon Sep 17 00:00:00 2001 From: Dan Jacob Date: Sat, 27 Feb 2021 16:49:06 +0200 Subject: [PATCH] Class decorator and test --- django_components/component.py | 17 +++++++++++++++++ tests/test_component.py | 8 ++++++++ 2 files changed, 25 insertions(+) diff --git a/django_components/component.py b/django_components/component.py index 294167b0..36bbe3b9 100644 --- a/django_components/component.py +++ b/django_components/component.py @@ -97,3 +97,20 @@ def is_slot_node(node): # This variable represents the global component registry registry = ComponentRegistry() + +def register(name): + """Class decorator to register a component. + + + Usage: + + @register("my_component") + class MyComponent(component.Component): + ... + + """ + def decorator(component): + registry.register(name=name, component=component) + return component + + return decorator diff --git a/tests/test_component.py b/tests/test_component.py index 1f02f6e1..ce28a023 100644 --- a/tests/test_component.py +++ b/tests/test_component.py @@ -9,6 +9,14 @@ from .testutils import Django111CompatibleSimpleTestCase as SimpleTestCase class ComponentRegistryTest(SimpleTestCase): + + def test_register_class_decorator(self): + @component.register("decorated_component") + class TestComponent(component.Component): + pass + + self.assertEqual(component.registry.get("decorated_component"), TestComponent) + def test_empty_component(self): class EmptyComponent(component.Component): pass