Add 'config()' and 'state()' functions directly to 'Rocket' for convenience.

This commit is contained in:
Jeb Rosen 2020-06-14 08:57:54 -07:00 committed by Sergio Benitez
parent 85b3259120
commit e72058de81
8 changed files with 55 additions and 13 deletions

View File

@ -94,7 +94,7 @@ pub fn database_attr(attr: TokenStream, input: TokenStream) -> Result<TokenStrea
use #databases::Poolable;
::rocket::fairing::AdHoc::on_attach(#fairing_name, |mut rocket| async {
let pool = #databases::database_config(#name, rocket.inspect().await.config())
let pool = #databases::database_config(#name, rocket.config().await)
.map(<#conn_type>::pool);
match pool {

View File

@ -550,15 +550,15 @@ pub enum ConfigError {
/// #
/// # rocket::custom(config).attach(AdHoc::on_attach("Testing", |mut rocket| async {
/// # {
/// let manifest = rocket.inspect().await;
/// let config = database_config("my_db", manifest.config()).unwrap();
/// let rocket_config = rocket.config().await;
/// let config = database_config("my_db", rocket_config).unwrap();
/// assert_eq!(config.url, "db/db.sqlite");
/// assert_eq!(config.pool_size, 25);
///
/// let other_config = database_config("my_other_db", manifest.config()).unwrap();
/// let other_config = database_config("my_other_db", rocket_config).unwrap();
/// assert_eq!(other_config.url, "mysql://root:root@localhost/database");
///
/// let error = database_config("invalid_db", manifest.config()).unwrap_err();
/// let error = database_config("invalid_db", rocket_config).unwrap_err();
/// assert_eq!(error, ConfigError::MissingKey);
/// # }
/// #

View File

@ -152,8 +152,7 @@ impl Fairing for TemplateFairing {
/// template engines. In debug mode, the `ContextManager::new` method
/// initializes a directory watcher for auto-reloading of templates.
async fn on_attach(&self, mut rocket: Rocket) -> Result<Rocket, Rocket> {
let manifest = rocket.inspect().await;
let config = manifest.config();
let config = rocket.config().await;
let mut template_root = config.root_relative(DEFAULT_TEMPLATE_DIR);
match config.get_str("template_dir") {
Ok(dir) => template_root = config.root_relative(dir),

View File

@ -176,7 +176,7 @@
//! rocket::ignite()
//! .attach(AdHoc::on_attach("Token Config", |mut rocket| async {
//! println!("Adding token managed state from config...");
//! let token_val = rocket.inspect().await.config().get_int("token").unwrap_or(-1);
//! let token_val = rocket.config().await.get_int("token").unwrap_or(-1);
//! Ok(rocket.manage(Token(token_val)))
//! }))
//! # ;

View File

@ -1012,6 +1012,49 @@ impl Rocket {
self.actualize_manifest().await;
self._manifest()
}
/// Returns `Some` of the managed state value for the type `T` if it is
/// being managed by `self`. Otherwise, returns `None`.
///
/// This function is equivalent to `.inspect().await.state()` and is
/// provided as a convenience.
///
/// # Example
///
/// ```rust
/// #[derive(PartialEq, Debug)]
/// struct MyState(&'static str);
///
/// # rocket::async_test(async {
/// let mut rocket = rocket::ignite().manage(MyState("hello!"));
/// assert_eq!(rocket.state::<MyState>().await, Some(&MyState("hello!")));
/// # });
/// ```
pub async fn state<T: Send + Sync + 'static>(&mut self) -> Option<&T> {
self.inspect().await.state()
}
/// Returns the active configuration.
///
/// This function is equivalent to `.inspect().await.config()` and is
/// provided as a convenience.
///
/// # Example
///
/// ```rust
/// # #![feature(proc_macro_hygiene)]
/// # #[macro_use] extern crate rocket;
/// use rocket::Rocket;
/// use rocket::fairing::AdHoc;
///
/// # rocket::async_test(async {
/// let mut rocket = rocket::ignite();
/// println!("Rocket config: {:?}", rocket.config().await);
/// # });
/// ```
pub async fn config(&mut self) -> &Config {
self.inspect().await.config()
}
}
impl Manifest {
@ -1120,8 +1163,8 @@ impl Manifest {
/// fn main() {
/// # if false { // We don't actually want to launch the server in an example.
/// rocket::ignite()
/// .attach(AdHoc::on_launch("Config Printer", |rocket| {
/// println!("Rocket launch config: {:?}", rocket.config());
/// .attach(AdHoc::on_launch("Config Printer", |manifest| {
/// println!("Rocket launch config: {:?}", manifest.config());
/// }))
/// .launch();
/// # }

View File

@ -57,7 +57,7 @@ pub fn test_config(environment: Environment) {
let rocket = rocket::ignite()
.attach(AdHoc::on_attach("Local Config", |mut rocket| async {
println!("Attaching local config.");
let config = rocket.inspect().await.config().clone();
let config = rocket.config().await.clone();
Ok(rocket.manage(LocalConfig(config)))
}))
.mount("/", routes![check_config]);

View File

@ -69,7 +69,7 @@ fn rocket() -> rocket::Rocket {
.attach(Counter::default())
.attach(AdHoc::on_attach("Token State", |mut rocket| async {
println!("Adding token managed state...");
let token_val = rocket.inspect().await.config().get_int("token").unwrap_or(-1);
let token_val = rocket.config().await.get_int("token").unwrap_or(-1);
Ok(rocket.manage(Token(token_val)))
}))
.attach(AdHoc::on_launch("Launch Message", |_| {

View File

@ -210,7 +210,7 @@ fn main() {
rocket::ignite()
.mount("/", routes![assets])
.attach(AdHoc::on_attach("Assets Config", |mut rocket| {
let assets_dir = rocket.inspect().await.config()
let assets_dir = rocket.config().await
.get_str("assets_dir")
.unwrap_or("assets/")
.to_string();