Skip to content

Commit

Permalink
resource: fix resource from model lookup now uses hierarchy correctly
Browse files Browse the repository at this point in the history
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
robvdl committed Mar 14, 2024
1 parent 1267ca4 commit 73f5544
Showing 1 changed file with 28 additions and 3 deletions.
31 changes: 28 additions & 3 deletions src/sambal/resources/resource.py
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

0 comments on commit 73f5544

Please sign in to comment.