require 'rubygems' require "active_support/all" class TimeMath private_class_method :new TIME_COMPONENTS = [:add, :diff] def self.strftime(time_a, time_b) new(time_a, time_b, "strftime") end def self.realtime(time_a, time_b) new(time_a, time_b, "realtime") end def sum case @consumer when "strftime" strftime_sum when "realtime" # TODO else "Nothing here!" end end def diff case @consumer when "strftime" strftime_diff when "realtime" realtime_diff(@time_a, @time_b) else "Nothing here!" end end private def initialize(time_a, time_b, consumer) @time_a = time_a @time_b = time_b @consumer = consumer end def strftime_sum itime_a = convert_strftime(@time_a) itime_b = convert_strftime(@time_b) construct_strftime((itime_a + itime_b)) end def strftime_diff itime_a = convert_strftime(@time_a) itime_b = convert_strftime(@time_b) time = itime_a - itime_b if time < 0 construct_strftime(time * -1) else construct_strftime(time) end end def realtime_diff(time_a, time_b) time = (time_a - time_b).to_i.abs hr = time / 3600 min = (time % 3600) / 60 sec = (time % 3600) % 60 "#{hr.to_s.rjust(2, '0')}:#{min.to_s.rjust(2, '0')}:#{sec.to_s.rjust(2, '0')}" end def convert_strftime(strftime) time = strftime.split(":") (time[0].to_i * 3600) + (time[1].to_i * 60) + (time[2].to_i) end def construct_strftime(time) hr = time / 3600 min = (time % 3600) / 60 sec = (time % 3600) % 60 "#{hr.to_s.rjust(2, '0')}:#{min.to_s.rjust(2, '0')}:#{sec.to_s.rjust(2, '0')}" end end