simple_translate_json/lib.rs
1//! Simple mini library made for translations (JSON)
2//!
3//! Provides system for language translation using serde_json, include_dir and sys_locale
4//! The library was made because i couldn't find any simple language library like that
5//!
6//! The library simply takes a language directory (that is a include_dir), then searched for a file with the same name as the locale
7//! The locale file name should be for example `en-us.json` (it has to be lowercase)
8//!
9//! Example usage:
10//! ```rust
11//! use include_dir::{Dir, include_dir};
12//! use sys_locale::get_locale;
13//! use simple_translate_json::Translation;
14//!
15//! const LANG_DIR: Dir = include_dir!("lang");
16//! let result = Translation::new(get_locale(), LANG_DIR);
17//! assert_eq!(result.get("title"), "example");
18//! ```
19//! lang/en-us.json
20//! ```json
21//! {
22//! "title": "example"
23//! }
24//! ```
25
26use std::collections::HashMap;
27use include_dir::{Dir, File};
28use serde_json::from_str;
29
30/// Struct holding the translation
31pub struct Translation {
32 translation: HashMap<String, String>,
33}
34
35impl Translation {
36 /// Create a new translation instance
37 pub fn new(language: Option<String>, language_dir: Dir) -> Self {
38 if language.is_none() {
39 return Translation::default(language_dir)
40 }
41
42 let language = language.unwrap();
43 let file = language_dir.get_file(format!("{language}.json"));
44
45 if file.is_none() {
46 println!("Unsupported language: {language}");
47 return Translation::default(language_dir)
48 }
49
50 Translation {
51 translation: json_file_into_hashmap(file.unwrap()),
52 }
53 }
54
55 /// Get the translation from key
56 pub fn get(&self, key: &str) -> String {
57 self.translation.get(key).unwrap_or(&key.to_string()).to_string()
58 }
59
60 fn default(language_dir: Dir) -> Self {
61 let file = language_dir.get_file("en-us.json").unwrap();
62 Translation {
63 translation: json_file_into_hashmap(file),
64 }
65 }
66}
67fn json_file_into_hashmap(file: &File) -> HashMap<String, String> {
68 let contents = file.contents_utf8().unwrap();
69 from_str::<HashMap<String, String>>(contents).unwrap()
70}