Class: Fluffle::Handlers::Dispatcher

Inherits:
Base
  • Object
show all
Defined in:
lib/fluffle/handlers/dispatcher.rb

Overview

Lightweight DSL for defining handler blocks for a given message

Examples

dispatcher = Fluffle::Handlers::Dispatcher.new
dispatcher.handle('upcase') { |str| str.upcase }

# Also exposed through the `Fluffle::Server#drain` method
server.drain do |dispatcher|
  dispatcher.handle('upcase') { |str| str.upcase }
end

Instance Method Summary collapse

Constructor Details

#initialize {|_self| ... } ⇒ Dispatcher

Returns a new instance of Dispatcher.

Yields:

  • (_self)

Yield Parameters:



16
17
18
19
20
# File 'lib/fluffle/handlers/dispatcher.rb', line 16

def initialize
  @routes = []

  yield self if block_given?
end

Instance Method Details

#call(method:, params:, **_) ⇒ Object

Raises:

  • (NoMethodError)


28
29
30
31
32
33
34
35
36
# File 'lib/fluffle/handlers/dispatcher.rb', line 28

def call(method:, params:,  **_)
  @routes.each do |(pattern, block)|
    next if pattern != method

    return block.call(*params)
  end

  raise NoMethodError, "Undefined method '#{method}'"
end

#handle(pattern, &block) ⇒ Object

pattern - Right now just a String that 1-to-1 matches the ‘method` block - Block to call with the `params`



24
25
26
# File 'lib/fluffle/handlers/dispatcher.rb', line 24

def handle(pattern, &block)
  @routes << [pattern, block]
end