Skip to content

Commit

Permalink
Merge pull request #10 from daizutabi/9-add-context-method
Browse files Browse the repository at this point in the history
Add context method
  • Loading branch information
daizutabi authored Oct 3, 2024
2 parents b78f51d + cc83f76 commit 2056049
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 1 deletion.
8 changes: 7 additions & 1 deletion src/textconf/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@
class Renderable(ABC):
"""Represent a renderable class."""

@classmethod
def context(cls, cfg: Self) -> dict[str, Any]: # noqa: ARG003
"""Get the context for rendering."""
return {}

@classmethod
@abstractmethod
def render(cls, cfg: Self, *args, **kwargs) -> str:
Expand Down Expand Up @@ -67,7 +72,8 @@ def render(cls, cfg: Self, *args: dict[str, Any] | list[str], **kwargs) -> str:
in any of the searched directories.
"""
params = kwargs.copy()
params = cls.context(cfg)
params.update(kwargs)

for name, obj in iter_template_methods(cls):
if name not in params:
Expand Down
24 changes: 24 additions & 0 deletions tests/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,3 +94,27 @@ def test_render_endswith_raises():
cfg = Config(x=5)
with pytest.raises(AssertionError):
assert_render_endswith(cfg, "|Zzz")


@dataclass
class Context(BaseConfig):
_template_: str = "template.jinja"
x: int = 0

@classmethod
def context(cls, cfg: Self) -> dict[str, int | str]:
y = cls.y(cfg)
return {"y": y, "z": cls.z(cfg, y)}

@classmethod
def y(cls, cfg: Self) -> int:
return 2 * cfg.x

@classmethod
def z(cls, cfg: Self, y: int) -> str:
return "z" * (cfg.x + y)


def test_context():
cfg = Context(x=2)
assert_render_eq(cfg, "X2|Y4|Zzzzzzz")

0 comments on commit 2056049

Please sign in to comment.