Implement a basic event dispatcher
This commit is contained in:
parent
49fe77ddb1
commit
84ad217d5b
@ -1,6 +1,7 @@
|
|||||||
require 'uh'
|
require 'uh'
|
||||||
|
|
||||||
require 'uh/wm/cli'
|
require 'uh/wm/cli'
|
||||||
|
require 'uh/wm/dispatcher'
|
||||||
require 'uh/wm/env'
|
require 'uh/wm/env'
|
||||||
require 'uh/wm/manager'
|
require 'uh/wm/manager'
|
||||||
require 'uh/wm/runner'
|
require 'uh/wm/runner'
|
||||||
|
27
lib/uh/wm/dispatcher.rb
Normal file
27
lib/uh/wm/dispatcher.rb
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
module Uh
|
||||||
|
module WM
|
||||||
|
class Dispatcher
|
||||||
|
attr_reader :hooks
|
||||||
|
|
||||||
|
def initialize hooks = Hash.new
|
||||||
|
@hooks = hooks
|
||||||
|
end
|
||||||
|
|
||||||
|
def [] *key
|
||||||
|
@hooks[translate_key key] or []
|
||||||
|
end
|
||||||
|
|
||||||
|
def on *key, &block
|
||||||
|
@hooks[translate_key key] ||= []
|
||||||
|
@hooks[translate_key key] << block
|
||||||
|
end
|
||||||
|
|
||||||
|
|
||||||
|
private
|
||||||
|
|
||||||
|
def translate_key key
|
||||||
|
key.one? ? key[0] : key
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
44
spec/uh/wm/dispatcher_spec.rb
Normal file
44
spec/uh/wm/dispatcher_spec.rb
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
module Uh
|
||||||
|
module WM
|
||||||
|
RSpec.describe Dispatcher do
|
||||||
|
let(:hooks) { {} }
|
||||||
|
subject(:dispatcher) { described_class.new hooks }
|
||||||
|
|
||||||
|
describe '#[]' do
|
||||||
|
context 'when given key for existing hook' do
|
||||||
|
let(:hooks) { { hook_key: [:hook] } }
|
||||||
|
|
||||||
|
it 'returns registered hooks for this key' do
|
||||||
|
expect(dispatcher[:hook_key]).to eq [:hook]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when given multiple keys for existing hook' do
|
||||||
|
let(:hooks) { { %i[hook key] => [:hook] } }
|
||||||
|
|
||||||
|
it 'returns registered hooks for this key' do
|
||||||
|
expect(dispatcher[:hook, :key]).to eq [:hook]
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
context 'when given key for unknown hook' do
|
||||||
|
it 'returns an empty array' do
|
||||||
|
expect(dispatcher[:unknown_hook]).to eq []
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
|
||||||
|
describe '#on' do
|
||||||
|
it 'registers given hook for given key' do
|
||||||
|
dispatcher.on(:hook_key) { :hook }
|
||||||
|
expect(dispatcher.hooks[:hook_key]).to be
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'registers given hook for given multiple keys' do
|
||||||
|
dispatcher.on(:hook, :key) { :hook }
|
||||||
|
expect(dispatcher.hooks[%i[hook key]]).to be
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
||||||
|
end
|
Loading…
x
Reference in New Issue
Block a user