Class: Dry::System::Loader

Inherits:
Object
  • Object
show all
Defined in:
lib/dry/system/loader.rb,
lib/dry/system/loader/autoloading.rb

Overview

Default component loader implementation

This class is configured by default for every System::Container. You can provide your own and use it in your containers too.

Examples:

class MyLoader < Dry::System::Loader
  def call(*args)
    constant.build(*args)
  end
end

class MyApp < Dry::System::Container
  configure do |config|
    # ...
    config.component_dirs.loader = MyLoader
  end
end

Direct Known Subclasses

Autoloading

Defined Under Namespace

Classes: Autoloading

Class Method Summary collapse

Class Method Details

.call(component, *args) ⇒ Object

Returns an instance of the component

Provided optional args are passed to object’s constructor

Parameters:

  • args (Array)

    Optional constructor args

Returns:

  • (Object)


46
47
48
49
50
51
52
53
54
55
56
# File 'lib/dry/system/loader.rb', line 46

def call(component, *args)
  require!(component)

  constant = self.constant(component)

  if singleton?(constant)
    constant.instance(*args)
  else
    constant.new(*args)
  end
end

.constant(component) ⇒ Class

Returns the component’s class constant

Returns:

  • (Class)


64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/dry/system/loader.rb', line 64

def constant(component)
  inflector = component.inflector
  const_name = inflector.camelize(component.const_path)
  inflector.constantize(const_name)
rescue NameError => e
  # Ensure it's this component's constant, not any other NameError within the component
  if e.message =~ /#{const_name}( |\n)/
    raise ComponentNotLoadableError.new(component, e)
  else
    raise e
  end
end

.require!(component) ⇒ Object

Requires the component’s source file



32
33
34
35
# File 'lib/dry/system/loader.rb', line 32

def require!(component)
  require(component.require_path)
  self
end