Method: Hanami::Slice::ClassMethods#register_provider

Defined in:
lib/hanami/slice.rb

#register_provider(name, namespace: nil, from: nil, source: nil) ⇒ container

Registers a provider and its lifecycle hooks.

In most cases, you should call this from a dedicated file for the provider in your app or slice’s config/providers/ dir. This allows the provider to be loaded when individual matching components are resolved (for prepared slices) or when slices are booted.

Examples:

Simple provider

# config/providers/db.rb
Hanami.app.register_provider(:db) do
  start do
    require "db"
    register("db", DB.new)
  end
end

Provider with lifecycle steps, also using dependencies from the target container

# config/providers/db.rb
Hanami.app.register_provider(:db) do
  prepare do
    require "db"
    db = DB.new(target_container["settings"].database_url)
    register("db", db)
  end

  start do
    container["db"].establish_connection
  end

  stop do
    container["db"].close_connection
  end
end

Probvider registration under a namespace

# config/providers/db.rb
Hanami.app.register_provider(:persistence, namespace: true) do
  start do
    require "db"

    # Namespace option above means this will be registered as "persistence.db"
    register("db", DB.new)
  end
end

Parameters:

  • name (Symbol)

    the unique name for the provider

  • namespace (Boolean, String, nil) (defaults to: nil)

    register components from the provider with given namespace. May be an explicit string, or true for the namespace to be the provider’s name

  • from (Symbol, nil) (defaults to: nil)

    the group for an external provider source to use, with the provider source name inferred from name or passed explicitly as source:

  • source (Symbol, nil) (defaults to: nil)

    the name of the external provider source to use, if different from the value provided as name

  • if (Boolean)

    a boolean-returning expression to determine whether to register the provider

Returns:

Since:

  • 2.0.0

Since:

  • 2.0.0



538
539
540
# File 'lib/hanami/slice.rb', line 538

def register_provider(...)
  container.register_provider(...)
end