Pudu programming language
Menu
Package

@chrismichaelps / pudu-lang-validator

Typed fluent validation rules for Pudu

0.1.1Apache-2.01

InstallClose

Localization.pudu

Pudu42 lines1.4 KB

GitHub ↗
1/** @Validation.Localization.Catalog — resolves application message text */2module PuduLangValidator.Localization34import Std.Map as Map5import PuduLangValidator.Rule as Rule67/** @Validation.Localization.Catalog.Value — maps locale and code to text */8export type Catalog = { entries: Map[(Str, Str), Str] }910/// An empty application message catalog.11export fn empty() -> Catalog { Catalog{entries: mapOf([])} }1213/// Add or replace one message for a locale and rule code.14export fn withMessage(catalog: Catalog, locale: Str, code: Str, message: Str) -> Catalog {15  Catalog{entries: catalog.entries.insert((locale.toLower(), code), message)}16}1718/// Resolve exact locale, then language subtag, then caller fallback.19export fn messageFor(catalog: &Catalog, locale: Str, code: Str, fallback: Str) -> Str {20  let normalized = locale.toLower()21  match Map.get(&catalog.entries, (normalized, code)) {22    case Some(found) => found23    case None => {24      let language = normalized.split("-")[0]25      match Map.get(&catalog.entries, (language, code)) {26        case Some(found) => found27        case None => fallback28      }29    }30  }31}3233/// Use the model's locale to choose the latest rule's message.34export fn localized[T, V](35  builder: Rule.RuleBuilder[T, V], catalog: Catalog, locale: fn(T) -> Str,36  code: Str, fallback: Str37) -> Rule.RuleBuilder[T, V] {38  Rule.withMessageFrom(builder, fn(root: T, _value: V) -> Str {39      messageFor(&catalog, locale(root), code, fallback)40    })41}42