class Jerry::Config

A configuration specifies how to wire parts of an application

@abstract Subclass this class in order to create a configuration @example Basic usage

class Door; end
class Window; end

class House
  def initialize(door, window)
    # ...
  end
end

class MyConfig < Jerry::Config
  bind House, [Door, Window]
  bind Door
  bind Window
end

Attributes

jerry[W]

The jerry instance this config is part of

Public Class Methods

bind(klass, ctor_args = []) click to toggle source

Specify how to wire the dependencies of a given class

@param klass [Class] The class to wire the dependencies for @param ctor_args [Array<Class, Symbol, Proc>] specifies the arguments to

be given to the constructor

@return [Class] the class that will be instanciated

# File lib/jerry/config.rb, line 31
def bind(klass, ctor_args = [])
  named_bind klass, klass, ctor_args
end
named_bind(name, klass, ctor_args = []) click to toggle source

Specify how to wire the dependencies of a given class giving it a name

@param name [Symbol] The name used to identify this way of building the

given class

@param klass [Class] The class to wire the dependencies for @param ctor_args [Array<Class, Symbol, Proc>] specifies the arguments to

be given to the constructor

@return [Symbol] the name of the class that will be instanciated

# File lib/jerry/config.rb, line 43
def named_bind(name, klass, ctor_args = [])
  providers[name] = ClassProvider.new klass, ctor_args
  name
end
providers() click to toggle source
# File lib/jerry/config.rb, line 61
def providers
  @providers ||= {}
end
singleton(key) click to toggle source

Specifies that a class should only be instanciated once

@param key [Class, Symbol] the class or the name of the class that

should only be instanciated once
# File lib/jerry/config.rb, line 52
def singleton(key)
  return unless providers.key? key

  provider = providers[key]

  instance = nil
  providers[key] = ->(*args) { instance ||= provider.call(*args) }
end

Public Instance Methods

[](key) click to toggle source

@return an instance of an object wired by the config

# File lib/jerry/config.rb, line 70
def [](key)
  provider = self.class.providers[key]

  if provider
    provider.call @jerry, self
  else
    raise InstantiationError,
          "Failed to instanciate #{key}. Can't find provider for it"
  end
rescue RuntimeError
  raise InstantiationError, "Provider for #{key} raised an error"
end
knows?(key) click to toggle source

@return true if this config can provide the given key, false otherwise

# File lib/jerry/config.rb, line 84
def knows?(key)
  self.class.providers.key? key
end