Sha256: 39e10244d597fe80dfb7afe85b7f5a15571c77c00f960d490109eb3ec64d528a

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

require "work_timer/version"

module WorkTimer
  # Your code goes here...
  def self.greet
    'Hello'
  end
  
  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|
        # 標準で09:00:00となるのを00:00:00にするために60*60*15足してる
        workTime = (@endTime-@startTime.to_i+60*60*15).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.1 lib/work_timer.rb