Module: LSync::EventHandler

Included in:
Directory, Method, Script, Server
Defined in:
lib/lsync/event_handler.rb

Overview

Basic event handling and delegation.

Instance Method Summary collapse

Instance Method Details

#abort!(persistent = false) ⇒ Object

Abort the current event handler. Aborting an event handler persistently implies that in the future it will still be aborted; thus calling #try will have no effect.



58
59
60
61
62
# File 'lib/lsync/event_handler.rb', line 58

def abort!(persistent = false)
	@aborted = true if persistent
	
	throw abort_name
end

#fire(event, *args) ⇒ Object

Fire an event which calls all registered event handlers in the order they were defined.



15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/lsync/event_handler.rb', line 15

def fire(event, *args)
	handled = false
	
	if @events && @events[event]
		@events[event].each do |handler|
			handled = true
			handler.call(*args)
		end
	end
	
	return handled
end

#on(event, &block) ⇒ Object

Register an event handler which may be triggered when an event is fired.



7
8
9
10
11
12
# File 'lib/lsync/event_handler.rb', line 7

def on(event, &block)
	@events ||= {}

	@events[event] ||= []
	@events[event] << block
end

#try(*arguments) ⇒ Object

Try executing a given block of code and fire appropriate events.

The sequence of events (registered via #on) are as follows:

:prepare

Fired before the block is executed. May call #abort! to cancel execution.

:success

Fired after the block of code has executed without raising an exception.

:failure

Fired if an exception is thrown during normal execution.

:done

Fired at the end of execution regardless of failure.

If #abort! has been called in the past, this function returns immediately.



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/lsync/event_handler.rb', line 37

def try(*arguments)
	return if @aborted
	
	begin
		catch(abort_name) do
			fire(:prepare, *arguments)
			
			yield
			
			fire(:success, *arguments)
		end
	rescue Exception => error
		# Propagage the exception unless it was handled in some specific way.
		raise unless fire(:failure, *arguments + [error])
	ensure
		fire(:done, *arguments)
	end
end