From 1623fe15cc494db38e9665388487e9f03b9a4bf0 Mon Sep 17 00:00:00 2001 From: Tim Riley Date: Wed, 12 Jun 2024 22:16:05 +1000 Subject: [PATCH] Load providers when accessing via #[] Move the logic from `ProviderRegistrar#find_and_load_provider` straght into `#[]` for a more convenient and reliable experience when interacting with providers. Having `#[]` either return a provider or nil without attempting to _load_ the provider was a potential source of confusion. Now it can work as the one and only interface for fetching a provider. Remove the `#provider` alias for `#[]` since this was private and unused (and unnecessary). Remove `#start_provider_dependency` (which was the only thing in `ProviderRegistrar` dealing with components instead of providers and instead invoke its internal logic (a one-liner, anyway!) directly in `Container#load_component`. --- lib/dry/system/container.rb | 4 ++-- lib/dry/system/provider_registrar.rb | 31 +++++++--------------------- 2 files changed, 10 insertions(+), 25 deletions(-) diff --git a/lib/dry/system/container.rb b/lib/dry/system/container.rb index fd9dc321..b324f8e4 100644 --- a/lib/dry/system/container.rb +++ b/lib/dry/system/container.rb @@ -608,14 +608,14 @@ def inherited(klass) def load_component(key) return self if registered?(key) - if (provider = providers.find_and_load_provider(key)) + if (provider = providers[key]) provider.start return self end component = find_component(key) - providers.start_provider_dependency(component) + providers[component.root_key]&.start return self if registered?(key) if component.loadable? diff --git a/lib/dry/system/provider_registrar.rb b/lib/dry/system/provider_registrar.rb index ebafb359..6f078735 100644 --- a/lib/dry/system/provider_registrar.rb +++ b/lib/dry/system/provider_registrar.rb @@ -84,43 +84,28 @@ def register_provider(name, from: nil, source: nil, if: true, **provider_options # rubocop:enable Metrics/PerceivedComplexity - # Returns a provider for the given name, if it has already been loaded - # - # @api public - def [](provider_name) - providers[provider_name] - end - alias_method :provider, :[] - - # @api private - def key?(provider_name) - providers.key?(provider_name) - end - # Returns a provider if it can be found or loaded, otherwise nil # # @return [Dry::System::Provider, nil] # - # @api private - def find_and_load_provider(name) - name = name.to_sym + # @api public + def [](provider_name) + provider_name = provider_name.to_sym - if (provider = providers[name]) + if (provider = providers[provider_name]) return provider end return if finalized? - require_provider_file(name) + require_provider_file(provider_name) - providers[name] + providers[provider_name] end # @api private - def start_provider_dependency(component) - if (provider = find_and_load_provider(component.root_key)) - provider.start - end + def key?(provider_name) + providers.key?(provider_name) end # Returns all provider files within the configured provider_paths.