-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(static): make edtf more flexible
- Loading branch information
Showing
2 changed files
with
30 additions
and
11 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,18 +1,37 @@ | ||
from __future__ import annotations | ||
from typing import Callable | ||
from edtf import parse_edtf | ||
from edtf.parser.parser_classes import Date | ||
from edtf import parse_edtf, text_to_edtf | ||
from edtf.parser.parser_classes import Date, DateAndTime | ||
from edtf.parser.edtf_exceptions import EDTFParseException | ||
from ._base import ( | ||
ViewModel, | ||
) | ||
|
||
def _make_edtf(value: str, **config): | ||
# TODO: use the config! | ||
try: | ||
edtf = parse_edtf(value) | ||
except EDTFParseException: | ||
edtf = parse_edtf(text_to_edtf(value)) | ||
if isinstance(edtf, Date): | ||
return ExtendedDateViewModel(edtf) | ||
elif isinstance(edtf, DateAndTime): | ||
return ExtendedDateAndTimeViewModel(edtf) | ||
raise RuntimeError(f"Unrecognised EDTF class {type(edtf)} for {edtf}") | ||
|
||
class ExtendedDateViewModel(Date, ViewModel): | ||
"""Wraps a string, allowing language translation. | ||
# TODO: possibly slow, not very clean. | ||
def _add_view_model_class(obj, cls): | ||
obj.__class__ = cls.__class__(f"Extended{cls.__name__}ViewModel", (cls, ViewModel), {}) | ||
return obj | ||
|
||
Subclasses str, but also allows `.lang("zh")`, etc. to re-translate. | ||
""" | ||
class ExtendedDateAndTimeViewModel(DateAndTime, ViewModel): | ||
def __new__(cls, value: str | DateAndTime, **config): | ||
if isinstance(value, str): | ||
return _make_edtf(value, **config) | ||
return _add_view_model_class(value, DateAndTime) | ||
|
||
def __new__(cls, value: str, **config): | ||
# TODO: use the config! | ||
edtf = parse_edtf(value) | ||
return edtf | ||
class ExtendedDateViewModel(Date, ViewModel): | ||
def __new__(cls, value: str | Date, **config): | ||
if isinstance(value, str): | ||
return _make_edtf(value, **config) | ||
return _add_view_model_class(value, Date) |