From 877a3c95dd2de2f1796c2e6e587dc1dcbcd64520 Mon Sep 17 00:00:00 2001 From: "R. Tyler Croy" Date: Mon, 5 Jul 2021 09:23:18 -0700 Subject: [PATCH] Prepare Y10n for actual use --- README.adoc | 35 +++++++++++++++++++++++++++++++++++ src/lib.rs | 7 ++++--- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/README.adoc b/README.adoc index bc2e6f1..b834197 100644 --- a/README.adoc +++ b/README.adoc @@ -2,3 +2,38 @@ Yamlization (`y10n`) is a simple Rust-based localization (`l10n`) library. Strings can be defined in `.yml` files which are then merged together. + +Typically `y10n` should be used with multiple translation files written in +Yaml. The yaml files can be merged together to provide base translations (e.g. +the English strings) underneath the users preferred language (such as German). + +== Example + +.en.yml +[source,yaml] +---- +greeting: 'hello world' +---- + +.de.yml +[source,yaml] +---- +greeting: 'hallöchen kleiner Mann' +---- + + +.main.rs +[source,rust] +---- +use y10n::*; + +fn main() { + let y10n = Y10n::from_glob("l10n/**/*.yml"); + // Create Language entities based on an `Accept-Languages` header + let langs = parse_accept_languages("en,de;q=0.5"); + let translations = y10n.localize(&langs); + + // Translations is a serde_yaml::Value which can easily be brought into + // handlebars or other structures for interpolation +} +---- diff --git a/src/lib.rs b/src/lib.rs index 87c74b5..602e6e6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -18,6 +18,7 @@ lazy_static! { /** * Y10n is a stateful struct that can be loaded with localization files */ +#[derive(Clone, Debug)] pub struct Y10n { translations: HashMap, } @@ -35,7 +36,7 @@ impl Y10n { * For example `"l10n/**/*.yml"` will load all the yml files in the `l10n` directory using each * file's name (e.g. `en.yml`) to derive it's language key (`en`). */ - fn from_glob(pattern: &str) -> Self { + pub fn from_glob(pattern: &str) -> Self { let mut this = Self::new(); trace!( "Attempting to load translations from glob pattern: {:?}", @@ -68,7 +69,7 @@ impl Y10n { * Return a Vec of all the names of languages that have been loaded * These are conventionally just the file stems of the yml files loaded */ - fn languages(&self) -> Vec<&String> { + pub fn languages(&self) -> Vec<&String> { self.translations.keys().collect() } @@ -80,7 +81,7 @@ impl Y10n { * `en` file has 10, then this function could be called with a Vec of `Language` instances of * `[de, en]` and the result would contain the one German string and 9 English strings. */ - fn localize(&self, languages: &[Language]) -> serde_yaml::Value { + pub fn localize(&self, languages: &[Language]) -> serde_yaml::Value { use serde_yaml::{Mapping, Value}; let mut values = vec![];