Skip to main content

15_localized_assets/
15_localized_assets.rs

1use keket::{
2    database::{AssetDatabase, path::AssetPath},
3    fetch::{file::FileAssetFetch, rewrite::RewriteAssetFetch},
4    protocol::text::TextAssetProtocol,
5};
6use std::{
7    error::Error,
8    sync::{Arc, RwLock},
9};
10
11fn main() -> Result<(), Box<dyn Error>> {
12    /* ANCHOR: main */
13    let language = Arc::new(RwLock::new("en"));
14    let language2 = language.clone();
15
16    let mut database = AssetDatabase::default()
17        .with_protocol(TextAssetProtocol)
18        .with_fetch(RewriteAssetFetch::new(
19            FileAssetFetch::default().with_root("resources"),
20            move |path| {
21                // Rewrite input path to localized one.
22                Ok(AssetPath::from_parts(
23                    path.protocol(),
24                    &format!(
25                        "{}.{}{}",
26                        path.path_without_extension(),
27                        *language2.read().unwrap(),
28                        path.path_dot_extension().unwrap_or_default()
29                    ),
30                    path.meta(),
31                ))
32            },
33        ));
34
35    // Gets `text://localized.en.txt`.
36    let asset = database.ensure("text://localized.txt")?;
37    println!("English: {}", asset.access::<&String>(&database));
38
39    // Change language.
40    *language.write().unwrap() = "de";
41    database.storage.clear();
42
43    // Gets `text://localized.de.txt`.
44    let asset = database.ensure("text://localized.txt")?;
45    println!("German: {}", asset.access::<&String>(&database));
46    /* ANCHOR_END: main */
47
48    Ok(())
49}