Skip to main content

from_vars

Function from_vars 

Source
pub fn from_vars<'a, T: DeserializeOwned>(
    vars: impl IntoIterator<Item = (&'a str, &'a str)>,
) -> Result<T>
Expand description

Reads T from the given variables: what Ctx::config does with the Worker’s environment.

Use it in unit tests of code that takes the settings struct.

§Errors

Error::Internal when a required variable is missing or does not convert to its field’s type; the message names the variable and the fix.

§Examples

use serde::Deserialize;

#[derive(Debug, Deserialize, PartialEq)]
struct Settings {
    page_size: u32,
    admins: Vec<String>,
    debug_toolbar: Option<bool>,
}

let settings: Settings = ocre::config::from_vars([("PAGE_SIZE", "20"), ("ADMINS", "ada, grace")]).unwrap();
assert_eq!(settings, Settings { page_size: 20, admins: vec!["ada".into(), "grace".into()], debug_toolbar: None });

let err = ocre::config::from_vars::<Settings>([("PAGE_SIZE", "many")]).unwrap_err();
assert!(err.to_string().contains("`PAGE_SIZE`"));