Skip to main content

doido_controller/
initializers.rs

1//! Boot-time initializers (Rails `config/initializers/*`). Since initializers
2//! are code, not data, register named init functions and run them in order at
3//! boot; the first that errors stops the sequence.
4
5use doido_core::Result;
6
7type Init = Box<dyn FnOnce() -> Result<()> + Send>;
8
9/// An ordered registry of named initializers.
10#[derive(Default)]
11pub struct Initializers {
12    inits: Vec<(String, Init)>,
13}
14
15impl Initializers {
16    pub fn new() -> Self {
17        Self::default()
18    }
19
20    /// Register an initializer to run at boot.
21    pub fn register(
22        &mut self,
23        name: &str,
24        init: impl FnOnce() -> Result<()> + Send + 'static,
25    ) -> &mut Self {
26        self.inits.push((name.to_string(), Box::new(init)));
27        self
28    }
29
30    /// Names of registered initializers, in order.
31    pub fn names(&self) -> Vec<&str> {
32        self.inits.iter().map(|(n, _)| n.as_str()).collect()
33    }
34
35    /// Run every initializer in registration order; stop at the first error.
36    pub fn run_all(self) -> Result<()> {
37        for (name, init) in self.inits {
38            init().map_err(|e| doido_core::anyhow::anyhow!("initializer `{name}` failed: {e}"))?;
39        }
40        Ok(())
41    }
42}