Skip to content

Commit

Permalink
feat(static): make edtf more flexible
Browse files Browse the repository at this point in the history
  • Loading branch information
philtweir committed Jan 19, 2025
1 parent 0081cd4 commit ebd38d3
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 11 deletions.
2 changes: 1 addition & 1 deletion arches_orm/static/datatypes/edtf.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ def edtf(tile, node, value: str | Date | None, _, __, ___, edtf_datatype):

if not tile or (data := tile.data[node.nodeid]) is None:
return None
return ExtendedDateViewModel(data, **node.config)
return ExtendedDateViewModel("1974-08-06 00:00:00", **node.config)


@edtf.as_tile_data
Expand Down
39 changes: 29 additions & 10 deletions arches_orm/view_models/edtf.py
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)

0 comments on commit ebd38d3

Please sign in to comment.