Class: Lutaml::Store::Events

Inherits:
Object
  • Object
show all
Defined in:
lib/lutaml/store/events.rb

Instance Method Summary collapse

Constructor Details

#initialize(async: false) ⇒ Events

Returns a new instance of Events.



6
7
8
9
10
11
12
# File 'lib/lutaml/store/events.rb', line 6

def initialize(async: false)
  @listeners = Hash.new { |h, k| h[k] = [] }
  @mutex = Mutex.new
  @async = async
  @queue = async ? Queue.new : nil
  @worker_thread = async ? start_worker_thread : nil
end

Instance Method Details

#clear_listeners(event = nil) ⇒ Object



47
48
49
50
51
52
53
54
55
# File 'lib/lutaml/store/events.rb', line 47

def clear_listeners(event = nil)
  @mutex.synchronize do
    if event
      @listeners[event].clear
    else
      @listeners.clear
    end
  end
end

#emit(event, data = {}) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/lutaml/store/events.rb', line 30

def emit(event, data = {})
  listeners = @mutex.synchronize { @listeners[event].dup }
  return if listeners.empty?

  event_data = {
    event: event,
    timestamp: Time.now,
    **data
  }

  if @async
    @queue << [listeners, event_data]
  else
    notify_listeners(listeners, event_data)
  end
end

#listener_count(event) ⇒ Object



57
58
59
# File 'lib/lutaml/store/events.rb', line 57

def listener_count(event)
  @mutex.synchronize { @listeners[event].size }
end

#off(event, listener) ⇒ Object



24
25
26
27
28
# File 'lib/lutaml/store/events.rb', line 24

def off(event, listener)
  @mutex.synchronize do
    @listeners[event].delete(listener)
  end
end

#on(event, callable = nil, &block) ⇒ Object

Raises:

  • (ArgumentError)


14
15
16
17
18
19
20
21
22
# File 'lib/lutaml/store/events.rb', line 14

def on(event, callable = nil, &block)
  listener = callable || block
  raise ArgumentError, "No listener provided" unless listener
  raise ArgumentError, "Event must be a Symbol" unless event.is_a?(Symbol)

  @mutex.synchronize do
    @listeners[event] << listener
  end
end

#stopObject



61
62
63
64
65
66
67
# File 'lib/lutaml/store/events.rb', line 61

def stop
  return unless @async && @worker_thread

  @queue << :stop
  @worker_thread.join
  @worker_thread = nil
end