Refactor Dispatcher
This commit is contained in:
parent
811354b683
commit
0ad00f3b77
@ -3,21 +3,20 @@ module Uh
|
|||||||
class Dispatcher
|
class Dispatcher
|
||||||
attr_reader :hooks
|
attr_reader :hooks
|
||||||
|
|
||||||
def initialize hooks = Hash.new
|
def initialize
|
||||||
@hooks = hooks
|
@hooks = Hash.new { |h, k| h[k] = [] }
|
||||||
end
|
end
|
||||||
|
|
||||||
def [] *key
|
def [] *key
|
||||||
@hooks[translate_key key] or []
|
@hooks[translate_key key]
|
||||||
end
|
end
|
||||||
|
|
||||||
def on *key, &block
|
def on *key, &block
|
||||||
@hooks[translate_key key] ||= []
|
|
||||||
@hooks[translate_key key] << block
|
@hooks[translate_key key] << block
|
||||||
end
|
end
|
||||||
|
|
||||||
def emit *key
|
def emit *key
|
||||||
@hooks[translate_key key].tap { |o| o.each { |e| e.call } if o }
|
@hooks[translate_key key].each { |e| e.call }
|
||||||
end
|
end
|
||||||
|
|
||||||
|
|
||||||
|
@ -1,12 +1,11 @@
|
|||||||
module Uh
|
module Uh
|
||||||
module WM
|
module WM
|
||||||
RSpec.describe Dispatcher do
|
RSpec.describe Dispatcher do
|
||||||
let(:hooks) { {} }
|
subject(:dispatcher) { described_class.new }
|
||||||
subject(:dispatcher) { described_class.new hooks }
|
|
||||||
|
|
||||||
describe '#[]' do
|
describe '#[]' do
|
||||||
context 'when given key for existing hook' do
|
context 'when given key for existing hook' do
|
||||||
let(:hooks) { { hook_key: [:hook] } }
|
before { dispatcher.hooks[:hook_key] = [:hook] }
|
||||||
|
|
||||||
it 'returns registered hooks for this key' do
|
it 'returns registered hooks for this key' do
|
||||||
expect(dispatcher[:hook_key]).to eq [:hook]
|
expect(dispatcher[:hook_key]).to eq [:hook]
|
||||||
@ -14,7 +13,7 @@ module Uh
|
|||||||
end
|
end
|
||||||
|
|
||||||
context 'when given multiple keys for existing hook' do
|
context 'when given multiple keys for existing hook' do
|
||||||
let(:hooks) { { %i[hook key] => [:hook] } }
|
before { dispatcher.hooks[%i[hook key]] = [:hook] }
|
||||||
|
|
||||||
it 'returns registered hooks for this key' do
|
it 'returns registered hooks for this key' do
|
||||||
expect(dispatcher[:hook, :key]).to eq [:hook]
|
expect(dispatcher[:hook, :key]).to eq [:hook]
|
||||||
|
Loading…
x
Reference in New Issue
Block a user