-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
resource: fix resource from model lookup now uses hierarchy correctly
It keeps traversing the object hierarchy until it finds one that isn't None. If it gets exhausted (that shouldn't happen) it just returns Resource, but the last loop iteration should already do that as it hits "top". Also add some docstrings to resource.py Fixes #38
- Loading branch information
Showing
1 changed file
with
28 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,23 +1,48 @@ | ||
from typing import Type | ||
|
||
from samba.domain.models import Model | ||
|
||
# A lookup table object_class to Resource. | ||
# A lookup table object_class to Resource class. | ||
RESOURCES = {} | ||
|
||
|
||
class ResourceMeta(type): | ||
"""Resource metaclass automatically populates the RESOURCES lookup table. | ||
This lookup table is used by resource_for_model to find a resource for | ||
the given object class. | ||
""" | ||
|
||
def __new__(mcls, name, bases, namespace, **kwargs): | ||
cls = super().__new__(mcls, name, bases, namespace, **kwargs) | ||
RESOURCES[cls.model.get_object_class()] = cls | ||
return cls | ||
|
||
|
||
class Resource(dict, metaclass=ResourceMeta): | ||
"""Resource base class represents the object class "top" or the base Model. | ||
Create specific resources for each Model subclass inheriting of Resource. | ||
""" | ||
|
||
model = Model | ||
|
||
def __init__(self, request, obj): | ||
"""The constructor for non-container objects. | ||
Container objects need to fetch the children as well, regular objects | ||
don't have to do this and are simply an update of the current object. | ||
""" | ||
super().__init__() | ||
self.update(obj.as_dict()) | ||
|
||
@staticmethod | ||
def resource_for_model(model): | ||
return RESOURCES.get(model.get_object_class(), Resource) | ||
def resource_for_model(obj: Model) -> Type["Resource"]: | ||
"""Traverse object hierarchy in reverse finding the closest Resource""" | ||
object_hierarchy = reversed(obj.object_class) | ||
|
||
for object_class in object_hierarchy: | ||
if resource := RESOURCES.get(object_class): | ||
return resource | ||
|
||
return Resource |