Sha256: 45de55abda8cec486b0a2d9bf66d2e1b19629e13b67c99d132ab84a9c3f46db3

Contents?: true

Size: 1.47 KB

Versions: 1

Compression:

Stored size: 1.47 KB

Contents

module Nurse
  class DependencyContainer
    class UndefinedDependency < RuntimeError; end
    class DependencyAlreadyDefined < RuntimeError; end

    def define(dependency, &block)
      ensure_undefined(dependency)
      definitions[to_key(dependency)] = block
      self
    end

    def define!(dependency, &block)
      undefine(dependency)
      define(dependency, &block)
    end

    def defined?(dependency)
      definitions.has_key?(to_key(dependency))
    end

    def get(dependency)
      return nil unless self.defined?(dependency)

      key = to_key(dependency)

      unless instances.has_key?(key)
        instances[key] = definitions[key].call(self)
      end

      instances[key]
    end

    def fetch(dependency, &block)
      return get(dependency) if self.defined?(dependency)
      return block.call(dependency) if block_given?
      raise UndefinedDependency, "'#{dependency}' was not defined"
    end

    private

    def ensure_undefined(dependency)
      if self.defined?(to_key(dependency))
        raise DependencyAlreadyDefined.new(
          "Dependency '#{dependency}' was already defined"
        )
      end
    end

    def instances
      @instances ||= {}
    end

    def definitions
      @definitions ||= {}
    end

    def to_key(object)
      object.to_s.to_sym
    end

    def undefine(dependency)
      return unless self.defined?(dependency)
      key = to_key(dependency)
      definitions.delete(key)
      instances.delete(key)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
nurse-rb-1.0.0 lib/nurse/dependency_container.rb