Sha256: 0dfff9cd2992d30ceb889c10a11872b1be78885a2814c475323357bd624b8429

Contents?: true

Size: 1009 Bytes

Versions: 4

Compression:

Stored size: 1009 Bytes

Contents

module Commandoes
  class IAmACommandRegistry
    def initialize(storage: DefaultStorageStrategy)
      @storage = storage
    end

    def [](command)
      handlers.fetch(storage_strategy.call command) { NullHandler }.tap do |handler|
        yield handler if block_given?
      end
    end

    alias_method :find_by, :[]

  protected

    def handlers
      @handlers ||= {}
    end

    def storage_strategy
      @storage ||= DefaultStorageStrategy
    end

    def register(command, handler: nil)
      unless handler.nil?
        handlers[storage_strategy.call command] = handler
      end
    end
  end

  DefaultStorageStrategy = ->(command) do
    return command.class unless command.kind_of? Class
    command
  end

  class NullHandler
    def initialize(command)
      @command = command
    end

    def call
      puts "-" * 65
      puts " NO HANDLER REGISTERED FOR #{command.class.upcase}"
      puts "-" * 65
      puts command.inspect
    end

  private
    attr_reader :command
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
commandoes-0.1.4 lib/commandoes/registry.rb
commandoes-0.1.3 lib/commandoes/registry.rb
commandoes-0.1.2 lib/commandoes/registry.rb
commandoes-0.1.1 lib/commandoes/registry.rb