2010-10-03 21:00:33 +00:00
|
|
|
module Guard
|
2011-09-20 11:10:16 +00:00
|
|
|
|
|
|
|
# The interactor reads user input and triggers
|
|
|
|
# specific action upon them unless its locked.
|
|
|
|
#
|
|
|
|
# Currently the following actions are implemented:
|
2011-09-20 22:34:11 +00:00
|
|
|
#
|
2011-09-20 11:10:16 +00:00
|
|
|
# - stop, quit, exit, s, q, e => Exit Guard
|
|
|
|
# - reload, r, z => Reload Guard
|
|
|
|
# - pause, p => Pause Guard
|
|
|
|
# - Everything else => Run all
|
|
|
|
#
|
2011-08-30 19:13:51 +00:00
|
|
|
class Interactor
|
2011-05-06 17:29:24 +00:00
|
|
|
|
2011-09-20 18:54:21 +00:00
|
|
|
class LockException < Exception; end
|
|
|
|
class UnlockException < Exception; end
|
|
|
|
|
2011-09-01 21:24:45 +00:00
|
|
|
attr_reader :locked
|
|
|
|
|
2011-09-20 11:10:16 +00:00
|
|
|
# Initialize the interactor in unlocked state.
|
|
|
|
#
|
2011-08-30 19:13:51 +00:00
|
|
|
def initialize
|
|
|
|
@locked = false
|
|
|
|
end
|
2011-08-17 08:07:30 +00:00
|
|
|
|
2011-09-20 22:34:11 +00:00
|
|
|
# Start the interactor in its own thread.
|
2011-09-20 11:10:16 +00:00
|
|
|
#
|
2011-08-30 19:13:51 +00:00
|
|
|
def start
|
2011-08-13 14:43:32 +00:00
|
|
|
return if ENV["GUARD_ENV"] == 'test'
|
2011-09-20 11:10:16 +00:00
|
|
|
|
2011-09-19 20:27:05 +00:00
|
|
|
@thread = Thread.new do
|
2011-08-29 19:25:58 +00:00
|
|
|
loop do
|
2011-09-20 18:54:21 +00:00
|
|
|
begin
|
|
|
|
if !@locked && (entry = $stdin.gets)
|
|
|
|
entry.gsub! /\n/, ''
|
|
|
|
case entry
|
2011-09-20 22:34:11 +00:00
|
|
|
when 'stop', 'quit', 'exit', 's', 'q', 'e'
|
|
|
|
::Guard.stop
|
|
|
|
when 'reload', 'r', 'z'
|
|
|
|
::Guard.reload
|
|
|
|
when 'pause', 'p'
|
|
|
|
::Guard.pause
|
|
|
|
else
|
|
|
|
::Guard.run_all
|
2011-09-20 18:54:21 +00:00
|
|
|
end
|
2011-08-17 08:07:30 +00:00
|
|
|
end
|
2011-09-20 18:54:21 +00:00
|
|
|
rescue LockException
|
|
|
|
lock
|
|
|
|
rescue UnlockException
|
|
|
|
unlock
|
2011-08-13 14:43:32 +00:00
|
|
|
end
|
2010-10-03 21:00:33 +00:00
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2011-08-13 14:43:32 +00:00
|
|
|
|
2011-09-20 11:10:16 +00:00
|
|
|
# Lock the interactor.
|
|
|
|
#
|
2011-08-29 19:25:58 +00:00
|
|
|
def lock
|
2011-09-20 22:34:11 +00:00
|
|
|
if !@thread || @thread == Thread.current
|
2011-09-20 18:54:21 +00:00
|
|
|
@locked = true
|
|
|
|
else
|
|
|
|
@thread.raise(LockException)
|
|
|
|
end
|
2011-08-29 19:25:58 +00:00
|
|
|
end
|
2011-08-30 19:13:51 +00:00
|
|
|
|
2011-09-20 11:10:16 +00:00
|
|
|
# Unlock the interactor.
|
|
|
|
#
|
2011-08-29 19:25:58 +00:00
|
|
|
def unlock
|
2011-09-20 22:34:11 +00:00
|
|
|
if !@thread || @thread == Thread.current
|
2011-09-20 18:54:21 +00:00
|
|
|
@locked = false
|
|
|
|
else
|
|
|
|
@thread.raise(UnlockException)
|
|
|
|
end
|
2011-08-17 08:07:30 +00:00
|
|
|
end
|
|
|
|
|
2010-10-03 21:00:33 +00:00
|
|
|
end
|
2011-05-06 17:29:24 +00:00
|
|
|
end
|