Class: CrossTimeCalculation
- Inherits:
-
Object
- Object
- CrossTimeCalculation
- Defined in:
- lib/cross_time_calculation.rb
Defined Under Namespace
Classes: TimePoint
Instance Attribute Summary collapse
-
#time_points ⇒ Object
Returns the value of attribute time_points.
Instance Method Summary collapse
- #add(*time_begin_and_end) ⇒ Object
-
#data_valid? ⇒ Boolean
start time and end time interval is supposed to exist.
-
#initialize ⇒ CrossTimeCalculation
constructor
A new instance of CrossTimeCalculation.
- #total_seconds ⇒ Object
Constructor Details
#initialize ⇒ CrossTimeCalculation
Returns a new instance of CrossTimeCalculation.
7 8 9 |
# File 'lib/cross_time_calculation.rb', line 7 def initialize self.time_points = Array.new end |
Instance Attribute Details
#time_points ⇒ Object
Returns the value of attribute time_points.
5 6 7 |
# File 'lib/cross_time_calculation.rb', line 5 def time_points @time_points end |
Instance Method Details
#add(*time_begin_and_end) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
# File 'lib/cross_time_calculation.rb', line 11 def add *time_begin_and_end # init TimePoint pair tb = TimePoint.new(time_begin_and_end[0], :started_at) te = TimePoint.new(time_begin_and_end[1], :finished_at) # validate data raise "At least the begin time should exist" if not tb.t raise "The begin time should not larger than the end time" if te.t && (tb.t > te.t) # insert it and sort self.time_points << tb self.time_points << te if te.t self.time_points = self.time_points.uniq {|i| "#{i.t}#{i.status}" }.sort {|a, b| a.t.to_i <=> b.t.to_i } # TODO optimize search with idx loop do to_removes = [] self.time_points.each_with_index do |tp, idx| post_tp = self.time_points[idx+1] next if post_tp.nil? # delete the first one if they are all finished_at to_removes << tp if (tp.status == :finished_at) && (post_tp.status == :finished_at) # delete the later one if they are all started_at to_removes << post_tp if (tp.status == :started_at) && (post_tp.status == :started_at) end self.time_points -= to_removes break if data_valid? end return self end |
#data_valid? ⇒ Boolean
start time and end time interval is supposed to exist
57 58 59 60 61 62 63 64 |
# File 'lib/cross_time_calculation.rb', line 57 def data_valid? valids = [] self.time_points.each_slice(2) do |tp_start, tp_finish| next if tp_finish.nil? valids << (tp_start.status != tp_finish.status) end valids.count(false).zero? end |
#total_seconds ⇒ Object
44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/cross_time_calculation.rb', line 44 def total_seconds result = 0 self.time_points.each_slice(2) do |a| end_time = a[1] ? a[1].t : Time.now if a[0] && a[0].t t = (end_time - a[0].t) result += t end end result end |