Skip to content

Commit

Permalink
simplify page index serialisation
Browse files Browse the repository at this point in the history
  • Loading branch information
lukavdplas committed Aug 9, 2024
1 parent de61ed4 commit bc2b63a
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 22 deletions.
7 changes: 7 additions & 0 deletions backend/addcorpus/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -473,6 +473,13 @@ class PageType(models.TextChoices):
help_text='markdown contents of the documentation'
)

@property
def page_index(self):
'''Numerical index to determine the order in which pages should be displayed.
Based on the order in which `PageType` choices are declared.'''
indexed_values = enumerate(__class__.PageType.values)
return next((i for (i, value) in indexed_values if value == self.type), None)

def __str__(self):
return f'{self.corpus_configuration.corpus.name} - {self.type}'

Expand Down
22 changes: 1 addition & 21 deletions backend/addcorpus/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,29 +131,9 @@ def to_representation(self, value):
return render_documentation_context(content)


class ChoiceOrderSerializer(serializers.ChoiceField):
'''
Variant on the ChoiceField that serialises to the index in the choices array.
'''
def __init__(self, choices, **kwargs):
super().__init__(choices=choices, **kwargs)
self.index = {value: i for i, (value, label) in enumerate(choices)}

def to_internal_value(self, data):
return self.choices[data]

def to_representation(self, value):
key = super().to_representation(value)
return self.index[key]


class CorpusDocumentationPageSerializer(serializers.ModelSerializer):
type = PrettyChoiceField(choices = CorpusDocumentationPage.PageType.choices)
index = ChoiceOrderSerializer(
read_only=True,
source='type',
choices=CorpusDocumentationPage.PageType.choices,
)
index = serializers.IntegerField(source='page_index', read_only=True)
content = DocumentationTemplateField(read_only=True)
content_template = serializers.CharField(source='content')
corpus = serializers.SlugRelatedField(
Expand Down
11 changes: 10 additions & 1 deletion backend/addcorpus/tests/test_models.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from addcorpus.models import Corpus
from addcorpus.models import Corpus, CorpusDocumentationPage

def test_corpus_model(db):
corpus = Corpus(name = 'test_corpus')
Expand All @@ -9,3 +9,12 @@ def test_corpus_model(db):
corpus.delete()

assert not Corpus.objects.filter(name = corpus)

def test_corpus_documentation_page_model(db, basic_mock_corpus):
corpus = Corpus.objects.get(name=basic_mock_corpus)
page = CorpusDocumentationPage(
corpus_configuration=corpus.configuration,
type=CorpusDocumentationPage.PageType.LICENSE,
content='Do whatever you want.',
)
assert page.page_index == 2

0 comments on commit bc2b63a

Please sign in to comment.