Test Failed
Push — master ( dbcfcd...9757cc )
by Swen
01:36
created

LocalizedValue.deconstruct()   A

Complexity

Conditions 1

Size

Total Lines 10

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 1
c 1
b 0
f 0
dl 0
loc 10
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
1 1
from django.conf import settings
2 1
from django.utils import translation
3
4
5 1
class LocalizedValue:
6
    """Represents the value of a :see:LocalizedField."""
7
8 1
    def __init__(self, keys: dict=None):
9
        """Initializes a new instance of :see:LocalizedValue.
10
11
        Arguments:
12
            keys:
13
                The keys to initialize this value with. Every
14
                key contains the value of this field in a
15
                different language.
16
        """
17
18 1
        for lang_code, _ in settings.LANGUAGES:
19 1
            value = keys.get(lang_code) if keys else None
20 1
            setattr(self, lang_code, value)
21
22 1
    def get(self, language: str=None) -> str:
23
        """Gets the underlying value in the specified or
24
        primary language.
25
26
        Arguments:
27
            language:
28
                The language to get the value in.
29
30
        Returns:
31
            The value in the current language, or
32
            the primary language in case no language
33
            was specified.
34
        """
35
36 1
        language = language or translation.get_language()
37 1
        return getattr(self, language, None)
38
39 1
    def set(self, language: str, value: str):
40
        """Sets the value in the specified language.
41
42
        Arguments:
43
            language:
44
                The language to set the value in.
45
46
            value:
47
                The value to set.
48
        """
49
50 1
        setattr(self, language, value)
51 1
        return self
52
53 1
    def deconstruct(self) -> dict:
54
        """Deconstructs this value into a primitive type.
55
56
        Returns:
57
            A dictionary with all the localized values
58 1
            contained in this instance.
59 1
        """
60 1
61
        path = 'localized_fields.fields.LocalizedValue'
62 1
        return path, [self.__dict__], {}
63
64
    def __str__(self) -> str:
65
        """Gets the value in the current language, or falls
66
        back to the primary language if there's no value
67
        in the current language."""
68
69
        value = self.get()
70
        if not value:
71
            value = self.get(settings.LANGUAGE_CODE)
72
73
        return value or ''
74
75
    def __repr__(self):  # pragma: no cover
76
        """Gets a textual representation of this object."""
77
78
        return 'LocalizedValue<%s> 0x%s' % (self.__dict__, id(self))
79