Created
June 14, 2014 18:47
-
-
Save myobie/a38644e2846c282e33af to your computer and use it in GitHub Desktop.
$ ruby alarm.rb in 30 minutes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "curses" | |
require "monitor" | |
class Timer | |
def initialize(amount) | |
@amount = amount | |
end | |
def after(&blk) | |
@after = blk | |
self | |
end | |
def time | |
@thread = Thread.new do | |
sleep @amount | |
@after.() if @after | |
end | |
self | |
end | |
def stop | |
@thread.terminate if @thread | |
self | |
end | |
end | |
class NowString | |
attr_reader :x, :y, :string | |
def initialize | |
width = Curses::cols | |
@string = Time.now.strftime("%H:%M:%S") | |
@y = Curses::lines / 2 | |
@x = (width - @string.length) / 2 | |
end | |
def to_s | |
@string | |
end | |
end | |
class Noise | |
def start | |
@thread = Thread.new do | |
loop do | |
beep | |
sleep 0.1 | |
beep | |
sleep 0.1 | |
beep | |
sleep 0.8 | |
end | |
end | |
end | |
def beep | |
print "\a" | |
end | |
def stop | |
@thread.terminate if @thread | |
end | |
end | |
class KeyCatcher | |
include MonitorMixin | |
def initialize | |
super() | |
@keys = {} | |
end | |
def on(key, &blk) | |
@keys[key] ||= [] | |
@keys[key].push blk | |
end | |
def run(key) | |
synchronize do | |
(@keys[key] || []).each do |blk| | |
blk.call | |
end | |
end | |
end | |
def setup | |
loop do | |
if stuff = IO.select([$stdin], nil, nil, 1) | |
char = Curses.getch | |
run char | |
end | |
end | |
end | |
end | |
units = { | |
"minutes" => 60, | |
"minute" => 60, | |
"hours" => 60 * 60, | |
"hour" => 60 * 60 | |
}.freeze | |
amount, unit_name = ARGV[-2..-1] | |
amount = Integer(amount) | |
time = amount * units.fetch(unit_name) | |
noise = Noise.new | |
timer = Timer.new(time).after do | |
noise.start | |
end.time | |
shutdown = ->{ | |
timer.stop | |
Curses.close_screen | |
exit | |
} | |
Curses.init_screen | |
Signal.trap("INT") do |signo| | |
shutdown.() | |
end | |
Thread.new do | |
loop do | |
now = NowString.new | |
Curses.clear | |
Curses.setpos(now.y, now.x) | |
Curses.addstr(now.to_s) | |
Curses.setpos(now.y + 1, 0) | |
Curses.addstr("") | |
Curses.refresh | |
sleep 1 | |
end | |
end | |
key_catcher = KeyCatcher.new | |
key_catcher.on("q") do | |
shutdown.() | |
end | |
key_catcher.on(" ") do | |
noise.stop() | |
end | |
key_catcher.on("b") do | |
noise.start() | |
end | |
key_catcher.setup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment