Use your business objects
You can use business objects (the instances of the classes from your business model) directly with the rule engine, without converting them to dictionaries.
Arta processes mappings in the rules and actions to inject data into functions, as you saw in the simple example of this documentation.
The problem with dict
serialisation
Let’s consider the following example, representing a Car
with its Engine
which itself has attributes.
When following the regular usage of Arta, one would convert an instance of a Car
to a dictionary with a sort of serializer. A candidate code for this might be:
When using Pydantic
If you use Pydantic, you might directly use the model_dump
function in order to represent your object as a dictionnary object.
This way, you can write you conditions as follows:
This is where the mapping is important: to go through the engine
data and access the power
attribute. We serialised the object in a custom code but there might be a better solution with less code…
Transform any business object to a mapping
The solution to this issue is to use any business object as a mapping. In Python, any object may behave as such by subclassing Mapping
and implementing the abstract methods.
As an example, we provide the following mixin:
Now, we can make our business objects subclass this mixin:
Engine
and Car
now behave as mapping and it’s possible to access the attributes of Engine
from car using the dict’s getitem
strategy, such as:
Finaly, when using the RulesEngine.apply_rules
method, there is not longer need to convert your business objects to dictionaries, you can directly use them like: