diff options
author | Ryan Leckey <ryan@launchbadge.com> | 2017-01-27 11:14:28 -0800 |
---|---|---|
committer | Ryan Leckey <ryan@launchbadge.com> | 2017-01-27 11:15:21 -0800 |
commit | f3b6fd435478a129dbf6ede37d8881c7a55efc42 (patch) | |
tree | 9e9e3eb6be09f6a80d9ed7d49781a1d9afb4b380 /src/env.rs | |
parent | 3af8fb895f002c8e1a3728d64bfe901b3cab3dfc (diff) |
Move 'Envrionment' into its own source
Diffstat (limited to 'src/env.rs')
-rw-r--r-- | src/env.rs | 43 |
1 files changed, 43 insertions, 0 deletions
diff --git a/src/env.rs b/src/env.rs new file mode 100644 index 0000000..612b97d --- /dev/null +++ b/src/env.rs @@ -0,0 +1,43 @@ +use std::env; +use std::error::Error; + +use source; +use value::Value; + +#[derive(Clone)] +pub struct Environment { + /// Optional prefix that would restrict environment consideration + /// to only variables which begin with that prefix. + prefix: Option<String>, +} + +impl Environment { + pub fn new<'a, T>(prefix: T) -> Environment + where T: Into<Option<&'a str>> + { + Environment { prefix: prefix.into().map(String::from) } + } +} + +impl source::SourceBuilder for Environment { + fn build(&self) -> Result<Box<source::Source>, Box<Error>> { + Ok(Box::new(self.clone())) + } +} + +impl source::Source for Environment { + fn get(&self, key: &str) -> Option<Value> { + let mut env_key = String::new(); + + // Apply prefix + if let Some(ref prefix) = self.prefix { + env_key.push_str(prefix); + env_key.push('_'); + } + + env_key.push_str(&key.to_uppercase()); + + // Attempt to retreive environment variable and coerce into a Value + env::var(env_key.clone()).ok().map(Value::from) + } +} |