Why Gemfury? Push, build, and install  RubyGems npm packages Python packages Maven artifacts PHP packages Go Modules Debian packages RPM packages NuGet packages

Repository URL to install this package:

Details    
supplement / examples / teatimer
Size: Mime:
#!/usr/bin/env ruby

#
#  teatimer  --  Countdown timer
#

# This is an example application for the itimer library.
# Example:
#
#   $ teatimer 3m play bell.wav
#         # Count down 3 minutes and the exec the player.
#

require "supplement/itimer"


class TeaTimer

  M = 60
  H = 60 * M

  class <<self

    def from_str time
      seconds = case time
        when /m\z/ then Integer( $`) * M
        when /h\z/ then Integer( $`) * H
        else            divide_colons time
      end
      new seconds
    end

    def run time
      t = from_str time
      t.run
    end

    private

    def divide_colons time
      a = time.split ":", -1
      a.map! { |x| Integer( x) }
      a.reverse!
      r = a.shift
      if a.first then r += M * a.shift end
      if a.first then r += H * a.shift end
      a.empty? or raise "Illegal time spec: #{time}."
      r
    end

  end

  def initialize seconds
    @seconds = seconds
  end

  class Done < Exception ; end

  def run
    trap "SIGALRM" do
      @seconds -= 1
      print_rest
      raise Done if @seconds.zero?
    end
    Process.setitimer 1
    print_rest
    sleep
  rescue Done
    puts
  ensure
    trap "SIGALRM", "DEFAULT"
    Process.setitimer nil
  end

  private

  def print_rest
    $stdout.print "  \r%02d:%02d:%02d" %
                    [ @seconds / H, @seconds % H / M, @seconds % M]
    $stdout.flush
  end

end

TeaTimer.run $*.first =~ /\A\d+/ ? $*.shift : "3m"
exec *$* if $*.any?