Class: Gemwarrior::Timer

Inherits:
Object
  • Object
show all
Includes:
Observable
Defined in:
lib/gemwarrior/misc/timer.rb

Constant Summary collapse

DEFAULTS =
{
  duration_in_s: 5, 
  timer_name:    'timer', 
  background:    true,
  progress:      false,
  verbose:       false,
  command:       nil
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}, repl) ⇒ Timer

Returns a new instance of Timer.



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/gemwarrior/misc/timer.rb', line 21

def initialize(options = {}, repl)
  options = DEFAULTS.merge(options)

  self.duration_in_s  = options[:duration_in_s]
  self.timer_name     = options[:timer_name]
  self.background     = options[:background]
  self.progress       = options[:progress]
  self.verbose        = options[:verbose]
  self.command        = options[:command]

  add_observer(repl)
end

Instance Attribute Details

#backgroundObject

Returns the value of attribute background.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def background
  @background
end

#commandObject

Returns the value of attribute command.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def command
  @command
end

#duration_in_sObject

Returns the value of attribute duration_in_s.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def duration_in_s
  @duration_in_s
end

#progressObject

Returns the value of attribute progress.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def progress
  @progress
end

#timer_nameObject

Returns the value of attribute timer_name.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def timer_name
  @timer_name
end

#verboseObject

Returns the value of attribute verbose.



10
11
12
# File 'lib/gemwarrior/misc/timer.rb', line 10

def verbose
  @verbose
end

Instance Method Details

#runObject



42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/gemwarrior/misc/timer.rb', line 42

def run
  puts "#{timer_name} began at #{Time.now} for #{duration_in_s} seconds" if verbose

  end_time = Time.now + duration_in_s

  loop do
    sleep 1
    print '.' if progress
    if Time.now >= end_time
      return stop
    end
  end
end

#startObject



34
35
36
37
38
39
40
# File 'lib/gemwarrior/misc/timer.rb', line 34

def start
  if background
    Thread.start { self.run }
  else
    self.run
  end
end

#stopObject



56
57
58
59
60
# File 'lib/gemwarrior/misc/timer.rb', line 56

def stop
  puts "\n#{timer_name} ended at #{Time.now}" if verbose
  changed
  notify_observers(self.command) unless self.command.nil?
end