Class: Hark::Dispatcher

Inherits:
Object
  • Object
show all
Defined in:
lib/hark/dispatcher.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(handlers) ⇒ Dispatcher

Returns a new instance of Dispatcher.



33
34
35
36
# File 'lib/hark/dispatcher.rb', line 33

def initialize handlers
  @handlers = handlers
  freeze
end

Instance Attribute Details

#handlersObject (readonly)

Returns the value of attribute handlers.



31
32
33
# File 'lib/hark/dispatcher.rb', line 31

def handlers
  @handlers
end

Class Method Details

.from(*args, &block) ⇒ Object

from(:success) do

  "success"
end

from(success: ->{ "success" })

from do |on|
  on.success { "success" }
end


13
14
15
16
17
18
19
# File 'lib/hark/dispatcher.rb', line 13

def self.from(*args, &block)
  if block
    args << (args.last.is_a?(Symbol) ? {args.pop => block} : block)
  end

  new args.map{|o| to_handler(o) }.flatten.freeze
end

.to_handler(object) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'lib/hark/dispatcher.rb', line 21

def self.to_handler object
  case object
  when Listener then object.dispatcher.handlers
  when Dispatcher then object.handlers
  when Hash then AdHoc.new(object)
  when Proc then AdHoc.new(&object)
  else object
  end
end

Instance Method Details

#handle(method, *args, &block) ⇒ Object



42
43
44
45
46
47
48
# File 'lib/hark/dispatcher.rb', line 42

def handle method, *args, &block
  results = []
  handlers.each do |handler|
    results << handler.send(method, *args, &block) if handler.respond_to?(method)
  end
  results
end

#handles?(method) ⇒ Boolean

Returns:

  • (Boolean)


38
39
40
# File 'lib/hark/dispatcher.rb', line 38

def handles? method
  handlers.any? {|handler| handler.respond_to?(method) }
end