Skip to content

Commit

Permalink
✨ lang.dispatch(scope)
Browse files Browse the repository at this point in the history
  • Loading branch information
RF-Tar-Railt committed Nov 14, 2024
1 parent c5eb49f commit 77737ae
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/tarina/lang/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -157,6 +157,19 @@ def _get_scopes(root: Path) -> dict[str, dict[str, dict[str, str]]]:
return result


class _LangScope:
def __init__(self, scope: str):
self.scope = scope

def require(self, type: str, subtype: str | None = None, locale: str | None = None):
if subtype:
type = f"{type}.{subtype}"
return lang.require(self.scope, type, locale)

def set(self, type: str, content: str, locale: str | None = None):
return lang.set(self.scope, type, content, locale)


@final
class _LangConfig:
def __init__(self):
Expand Down Expand Up @@ -296,6 +309,9 @@ def set(self, scope: str, type: str, content: str, locale: str | None = None):
raise ValueError(self.__langs[locale]["lang"]["error.type"].format(target=type, locale=locale, scope=scope))
self.__langs[locale].setdefault(scope, {})[type] = content

def dispatch(self, scope: str) -> _LangScope:
return _LangScope(scope)

def __repr__(self):
return f"<LangConfig: {self.__locale}>"

Expand Down
3 changes: 3 additions & 0 deletions tests/test_main.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ def test_lang():
lang.select("test")
assert lang.require("lang", "error.type") == "test"
assert lang.require("lang", "error.locale") == "'{target}' 不是合法的语种"
scope_lang = lang.dispatch("lang")
assert scope_lang.require("error.type") == "test"
assert scope_lang.require("error.locale") == "'{target}' 不是合法的语种"
lang.load_file(Path(__file__).parent / "en-UK.yml")
assert lang.locales == {"zh-CN", "test", "en-US", "en-UK"}

Expand Down

0 comments on commit 77737ae

Please sign in to comment.