global_value

Values

pub fn create_with_unique_name(
  name: String,
  initialiser: fn() -> t,
) -> t

Create a global value using a function and a string name. The string name must be globally unique, e.g. the name of the module + the name of the function. If you pick a name that is not unique then two global values can collide at runtime, which can violate the type system and cause crashes or worse.

This is most likely useful in your test suite for shared things such as a database pool, assuming your test runner doesn’t have a way to specify shared state.

The value is held in persistent term storage on Erlang and in a singleton object on JavaScript, so accessing the value from any process is efficient, but you should have as few global values as possible. Ideally only have one per project and put all the global state in a single value.

Example

// 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
}
Search Document