Passed
Push — datapoints-package ( a11eff )
by Konstantinos
02:48
created

BroadcastingDatapointsFactory.create()   A

Complexity

Conditions 4

Size

Total Lines 32
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
eloc 13
nop 4
dl 0
loc 32
rs 9.75
c 0
b 0
f 0
1
from typing import Iterable
2
import attr
3
from so_magic.utils import Subject
4
from .datapoints.datapoints import DatapointsFactory, TabularData
5
6
import json
7
import logging
8
logger = logging.getLogger(__name__)
9
10
11
# TODO refactor to a composition (not inheritance) implementation of the below class
12
# reason is that it will be more evident that this class simply combines the
13
# features of 2 other classes (Subject & DatapointsFactory) to get the job done
14
@attr.s
15
class BroadcastingDatapointsFactory(DatapointsFactory):
16
    """Creates Datapoints objects and informs its subscribers when that happens.
17
18
    A factory class that informs its subscribers when a new object that
19
    implements the DatapointsInterface is created (following a request).
20
21
    Args:
22
        subject (Subject, optional): the subject of observation; the "thing" that others
23
                          listen to
24
    """
25
    subject: Subject = attr.ib(init=True, default=Subject([]))
26
    name: str = attr.ib(init=False, default='')
27
    # TODO check if above can be removed, along with self.name = getattr(args[0], 'name', '') in 'create' method
28
29
    def create(self, datapoints_factory_type: str, *args, **kwargs) -> Iterable:
30
        """Create new Datapoints and inform subscribers.
31
32
        The factory method that returns a new object of DatapointsInterface, by
33
        looking at the registered constructors to delegate the object creation.
34
35
        Args:
36
            datapoints_factory_type (str): the name of the "constructor" to use
37
38
        Raises:
39
            RuntimeError: [description]
40
41
        Returns:
42
            Iterable: instance implementing the DatapointsInterface
43
        """
44
        self.subject.name = kwargs.pop('id', kwargs.pop('name', kwargs.pop('file_path', '')))
45
        if kwargs:
46
            msg = f"Kwargs: [{', '.join(f'{k}: {v}' for k, v in kwargs.items())}]"
47
            raise RuntimeError("The 'create' method of DatapointsFactory does not support kwargs:", msg)
48
        self.subject.state = super().create(datapoints_factory_type, *args, **kwargs)
49
        # logger.debug(f"Created datapoints: {json.dumps({
50
        #     'datapoints': self.subject.state,
51
        #     'name': self.subject.name,
52
        # })}")
53
        print("Created datapoints: {}".format(json.dumps({
54
            'datapoints': str(self.subject.state),
55
            'name': self.subject.name,
56
        })))
57
        if args and not hasattr(self, '.name'):
58
            self.name = getattr(args[0], 'name', '')
59
        self.subject.notify()
60
        return self.subject.state
61