Skip to content

Commit fbac487

Browse files
committed
Add i18n fallback
1 parent 83c6453 commit fbac487

File tree

3 files changed

+39
-10
lines changed

3 files changed

+39
-10
lines changed

Cargo.lock

Lines changed: 1 addition & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ lazy_static = "1.2.0"
99
fluent = "0.5"
1010
fluent-bundle = "0.6.0"
1111
fluent-syntax = "0.9.0"
12+
fluent-locale = "0.4.1"
1213
rand = "0.6"
1314
regex = "1"
1415
rocket = "0.4.1"

src/i18n.rs

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -15,19 +15,51 @@ use std::io::prelude::*;
1515
use std::path::Path;
1616

1717
use fluent_bundle::{FluentBundle, FluentResource, FluentValue};
18+
use fluent_locale::negotiate_languages;
1819

1920
lazy_static! {
2021
static ref RESOURCES: HashMap<String, Vec<FluentResource>> = build_resources();
2122
static ref BUNDLES: HashMap<String, FluentBundle<'static>> = build_bundles();
2223
}
2324

25+
pub struct Fallback<A: AsRef<str>> {
26+
default: Option<&'static str>,
27+
availables: Vec<A>,
28+
}
29+
30+
impl<A: AsRef<str>> Fallback<A> {
31+
pub fn new(available_locales: Vec<A>) -> Self {
32+
Self {
33+
default: Some("en-US"),
34+
availables: available_locales,
35+
}
36+
}
37+
38+
pub fn order<'t, T: AsRef<str>>(&'t self, targets: &'t [T]) -> Vec<&'t str> {
39+
negotiate_languages(
40+
targets,
41+
&self.availables,
42+
self.default,
43+
&fluent_locale::NegotiationStrategy::Filtering,
44+
)
45+
}
46+
}
47+
2448
pub struct I18NHelper {
2549
bundles: &'static HashMap<String, FluentBundle<'static>>,
50+
fallback: Fallback<String>,
2651
}
2752

2853
impl I18NHelper {
2954
pub fn new() -> Self {
30-
Self { bundles: &*BUNDLES }
55+
let mut availables: Vec<String> = Vec::new();
56+
for key in RESOURCES.keys() {
57+
availables.push(key.clone());
58+
}
59+
Self {
60+
bundles: &*BUNDLES,
61+
fallback: Fallback::new(availables),
62+
}
3163
}
3264

3365
pub fn lookup(
@@ -58,17 +90,12 @@ impl I18NHelper {
5890
text_id: &str,
5991
args: Option<&HashMap<&str, FluentValue>>,
6092
) -> String {
61-
if let Some(val) = self.lookup(lang, text_id, args) {
62-
val
63-
} else if lang != "en-US" {
64-
if let Some(val) = self.lookup("en-US", text_id, args) {
65-
val
66-
} else {
67-
format!("Unknown localization {}", text_id)
93+
for l in self.fallback.order(&[lang]) {
94+
if let Some(val) = self.lookup(l, text_id, args) {
95+
return val;
6896
}
69-
} else {
70-
format!("Unknown localization {}", text_id)
7197
}
98+
format!("Unknown localization {}", text_id)
7299
}
73100
}
74101

0 commit comments

Comments
 (0)