Sha256: 1d4512c8cf17e9511678ccb378f16a0971e1f547b92eb2326639f825a3a8d534

Contents?: true

Size: 1.17 KB

Versions: 12

Compression:

Stored size: 1.17 KB

Contents

module Spank
  class Container
    def initialize
      @items = {}
      register(:container) { self }
    end

    def register(key, &block)
      component = Component.new(key, &block)
      components_for(key).push(component)
      component
    end

    def resolve(key)
      instantiate(components_for(key).first, key)
    end

    def resolve_all(key)
      components_for(key).map {|item| instantiate(item, key) }
    end

    def build(type)
      try("I could not create: #{type}"){ build!(type) }
    end

    def build!(type)
      constructor = type.instance_method('initialize')
      parameters = constructor.parameters.map do |req, parameter|
        resolve(parameter.to_sym)
      end
      type.send(:new, *parameters)
    end

    private

    def components_for(key)
      @items[key] = [] unless @items[key]
      @items[key]
    end

    def instantiate(component, key)
      raise ContainerError.new("#{key} is not a registered component.") unless component
      component.create(self)
    end

    def try(error = nil, &lambda)
      begin
        lambda.call
      rescue => e
        raise Spank::ContainerError.new(error ||= "Oops: #{e}")
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
spank-1.1.0 lib/spank/container.rb
spank-1.0.1441140881 lib/spank/container.rb
spank-1.0.1441140857 lib/spank/container.rb
spank-1.0.1441140848 lib/spank/container.rb
spank-1.0.1441140841 lib/spank/container.rb
spank-1.0.1441140834 lib/spank/container.rb
spank-1.0.1441140824 lib/spank/container.rb
spank-1.0.1441140809 lib/spank/container.rb
spank-1.0.1441140804 lib/spank/container.rb
spank-1.0.1441140793 lib/spank/container.rb
spank-1.0.1420314444 lib/spank/container.rb
spank-0.0.1393558686 lib/spank/container.rb