Class: Appstats::FriendlyTimer

Inherits:
Object
  • Object
show all
Defined in:
lib/appstats/friendly_timer.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ FriendlyTimer

Returns a new instance of FriendlyTimer.



7
8
9
10
# File 'lib/appstats/friendly_timer.rb', line 7

def initialize(data = {})
  @duration = data[:duration]
  start
end

Instance Attribute Details

#durationObject

Returns the value of attribute duration.



5
6
7
# File 'lib/appstats/friendly_timer.rb', line 5

def duration
  @duration
end

#start_timeObject

Returns the value of attribute start_time.



5
6
7
# File 'lib/appstats/friendly_timer.rb', line 5

def start_time
  @start_time
end

#stop_timeObject

Returns the value of attribute stop_time.



5
6
7
# File 'lib/appstats/friendly_timer.rb', line 5

def stop_time
  @stop_time
end

Class Method Details

.calculate_duration_to_s(duration_in_seconds) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/appstats/friendly_timer.rb', line 27

def self.calculate_duration_to_s(duration_in_seconds)
  return "N/A" if duration_in_seconds.nil?
  
  #TODO use sortable hash if ruby 1.9.2
  times = [ 60*60*24*365.0, 60*60*24.0, 60*60.0, 60.0, 1.0, 0.001]
  names = [ 'year','day','hour','minute','second', 'millisecond']
  
  times.each_with_index do |factor,index|
    adjusted_time = duration_in_seconds / factor
    next if (adjusted_time < 1 && factor != 0.001)
    adjusted_time = (adjusted_time * 100).round / 100.0
    adjusted_time = adjusted_time.round if adjusted_time == adjusted_time.round
    name = adjusted_time == 1 ? names[index] : names[index].pluralize
    return "#{adjusted_time} #{name}"
  end      
end

Instance Method Details

#duration_to_sObject



23
24
25
# File 'lib/appstats/friendly_timer.rb', line 23

def duration_to_s
  FriendlyTimer.calculate_duration_to_s(duration)
end

#startObject



12
13
14
15
# File 'lib/appstats/friendly_timer.rb', line 12

def start
  @start_time = Time.now
  @start_time
end

#stopObject



17
18
19
20
21
# File 'lib/appstats/friendly_timer.rb', line 17

def stop
  @stop_time = Time.now
  update_duration_as_required
  @stop_time
end