global_value

Create singleton values accessible anywhere in your application.

Package Version Hex Docs

If you are making a library then you probably should not be using this library at all! Do not try to hide state, instead write code in the functional way and pass data as an argument to functions.

If you are compiling to Erlang then there is almost always a better option than this library (most notably: ETS tables owned by your application), but it could still be useful in tests.

On Erlang especially this should only ever contain small values. If you are storing anything that isn’t small then this is not suitable solution.

gleam add global_value@1
// test/my_app_test.gleam
import database
import global_value

// Define the global data

pub type TestGlobalData {
  TestGlobalData(db: database.ConnectionPool)
}

// A function to get-or-create the global data.
// In this example the first time the global data is accessed the database
// connection is created, and then the following times the already-created
// database connection is used.
pub fn global_data() -> TestGlobalData {
  global_value.create_with_unique_name("my_app_test.global.data", fn() {
    TestGlobalData(db: database.create_connection_pool())
  })
}

// Use it in tests

pub fn first_test() {
  let globals = global_data()
  // ... use the database connection here
}

pub fn second_test() {
  let globals = global_data()
  // ... use the database connection here
}

Further documentation can be found at https://hexdocs.pm/global_value.

Search Document