Passed
Branch master (0fb205)
by Oleksandr
03:17
created

commons.events.Event.to_primitive()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 1
CRAP Score 1.4218

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 7
ccs 1
cts 4
cp 0.25
rs 10
c 0
b 0
f 0
cc 1
nop 2
crap 1.4218
1 1
import abc
2
3 1
from il2fb.commons.exceptions import IL2FBParsingException
4 1
from il2fb.commons.structures import BaseStructure
5
6
7 1
class Event(BaseStructure, metaclass=abc.ABCMeta):
8
  """Base event structure."""
9
10 1
  def __init__(self, **kwargs):
11
    for key in self.__slots__:
12
      setattr(self, key, kwargs[key])
13
14
    super(Event, self).__init__()
15
16 1
  @property
17 1
  def name(self):
18
    return self.__class__.__name__
19
20 1
  @abc.abstractproperty
21 1
  def verbose_name(self):
22
    """Human-readable name of event."""
23
24 1
  def to_primitive(self, context=None):
25
    primitive = super(Event, self).to_primitive(context)
26
    primitive.update({
27
      'name': self.name,
28
      'verbose_name': str(self.verbose_name),
29
    })
30
    return primitive
31
32
  def __repr__(self):
33
      return "<Event {0} {1}>".format(self.name, self.to_primitive())
34
35
36 1
class ParsableEvent(Event):
37
  """Base event which can be parsed from string."""
38 1
  transformers = tuple()
39
40 1
  @classmethod
41 1
  def transform(cls, data):
42
    for transformer in cls.transformers:
43
      transformer(data)
44
45
    return data
46
47 1
  @abc.abstractproperty
48 1
  def matcher(self):
49
    """A callable for matching strings."""
50
51 1
  @classmethod
52 1
  def from_s(cls, s):
53
    match = cls.matcher(s)
54
55
    if match:
56
      data = cls.transform(match.groupdict())
57
      return cls(**data)
58
59
60 1
class EventParsingException(IL2FBParsingException):
61
  ...
62