languages_rs/lib.rs
1//! # languages-rs
2//!
3//! An internationalization library for your applications.
4//!
5//! # Features
6//! - `JSON` or `TOML` languages files.
7//! - Only can use Objects, Arrays and Strings.
8//! - Customize the languages directory.
9//!
10//! # JSON Language File
11//! ```json
12//! {
13//! "hello_world": "Hello, world!",
14//! "home": {
15//! "title": "Home page",
16//! "description": "This is the home page."
17//! },
18//! "data": {
19//! "messages": [
20//! "Message 1",
21//! "Message 2"
22//! ]
23//! ]
24//! }
25//! ```
26//!
27//! # TOML Language File
28//! ```toml
29//! hello_world = "Hello, world!"
30//!
31//! [home]
32//! title = "Home page"
33//! description = "This is the home page."
34//!
35//! [data]
36//! messages = [
37//! "Message 1",
38//! "Message 2"
39//! ]
40//! ```
41//!
42//! # Basic Usage
43//! `languages/en.json`
44//! ```json
45//! {
46//! "hello_world": "Hello world!"
47//! }
48//! ```
49//!
50//! `src/main.rs`
51//! ```rust, ignore
52//! use languages_rs::{Config, Languages, load, Value};
53//!
54//! fn main() -> Result<()> {
55//! let mut configuration: Config = Config::default().unwrap();
56//! configuration.add_language("en").unwrap();
57//!
58//! // Load all default languages.
59//! let mut texts: Languages = load(configuration).unwrap();
60//!
61//! // Get the English texts from `/languages/es.json`.
62//! let texts_en: LanguagesTexts = texts.try_get_language("en").unwrap();
63//!
64//! // Get the `hello_world` text from English texts.
65//! let en_hello_world: Value = texts_en.try_get_text("hello_world").unwrap();
66//! assert!(en_hello_world.is_string());
67//!
68//! // Other alternative to get the `hello_world` text from English texts.
69//! let en_hello_world_2: Value = texts.try_get_text_from_language("en", "hello_world").unwrap();
70//! assert!(en_hello_world_2.is_string());
71//!
72//! assert_eq!(en_hello_world, en_hello_world_2);
73//! assert_eq!(en_hello_world.get_string(), en_hello_world_2.get_string());
74//! }
75//! ```
76
77mod config;
78mod languages;
79mod value;
80
81pub use config::Config;
82pub use languages::{LanguageTexts, Languages};
83pub use value::Value;
84
85/// Load the languages of a configuration and return the `Languages` struct.
86///
87/// # Example
88/// ```rust, ignore
89/// use languages_rs::{Config, load};
90///
91/// let mut config = Config::default();
92///
93/// // Add `en` language to the configuration.
94/// config.add_language("en").unwrap();
95///
96/// // This loads `languages/en.json` to the cache.
97/// let texts = load(config);
98/// ```
99pub fn load(configuration: Config) -> anyhow::Result<Languages> {
100 let mut languages = Languages::new(&configuration);
101
102 for lang in configuration.get_languages().iter() {
103 languages.try_get_language(lang)?;
104 }
105
106 Ok(languages)
107}