Sha256: 238e69e8a677921aa7b03d1760a6afbea9fe161a8d35ec36184a98961719597f

Contents?: true

Size: 1.71 KB

Versions: 1

Compression:

Stored size: 1.71 KB

Contents

require "work_timer/version"

module WorkTimer
  class Work
    def initialize(fileName)
      @fileName = fileName
    end

    def start_work(startTime=nil)
      @startTime ||= Time.now
    end

    def end_work(endTime=nil)
      @endTime ||= Time.now
      stop_view
    end

    # 戻り値はString
    def total_time
      totalTime = 0
      begin
        f = File.open(@fileName, "r")
      rescue
        return sec2seq(totalTime)
      end
      f.each_line do |line|
        next if line =~ /^\d{4}-\d{2}-\d{2}/
        # **:**:**表示を秒に変換
        line.chomp.split(":").each_with_index do |time, i|
          totalTime += time.to_i*60**(2-i)
        end
      end
      f.close
      sec2seq(totalTime)
    end

    def record_time
      File.open(@fileName, "a+") do |f|
        timezone = Time.now.strftime("%z").to_i/100
        workTime = (@endTime-@startTime.to_i+60*60*(24-timezone)).strftime("%T")
        f.puts @startTime, @endTime, workTime
      end
    end

    def view
      @view_thread = Thread.new do
        loop do
          workingTime = Time.now - @startTime.to_i
          print "\r\033[32m#{(workingTime+60*60*15).strftime("%T")}\033[30m"
          sleep 1
        end
      end
    end

    private

    def sec2seq(sec)
      hours = (sec/3600.0).to_i.to_s
      minutes = ((sec-(sec/3600.0).to_i*3600.0)/60).to_i.to_s
      seconds = (sec%60).to_i.to_s
      "#{two_digits(hours)}:#{two_digits(minutes)}:#{two_digits(seconds)}"
    end

    # 1桁の数字(実際はStringクラス)を2桁にする (e.g.: 0:0:47 -> 00:00:47)
    def two_digits(time)
      time.size==1 ? "0"+time : time
    end

    def stop_view
      @view_thread.kill if @view_thread && @view_thread.alive?
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
work_timer-0.1.2 lib/work_timer.rb