Class: Pocketwatch::Watcher

Inherits:
Object
  • Object
show all
Defined in:
lib/pocketwatch/watcher.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(command, options = {}) ⇒ Watcher

Returns a new instance of Watcher.

Parameters:

  • command (String)

    the command to run on an interval

  • options (Hash) (defaults to: {})

    the options hash determined by the command-line option parser



13
14
15
16
17
18
19
20
21
# File 'lib/pocketwatch/watcher.rb', line 13

def initialize(command, options = {})
  @command = command

  if @command.nil? || @command.empty?
    warn "No command provided."
    exit 1
  end
  @options = options
end

Instance Attribute Details

#commandString (readonly)

Returns the command to run on an interval.

Returns:

  • (String)

    the command to run on an interval



4
5
6
# File 'lib/pocketwatch/watcher.rb', line 4

def command
  @command
end

#optionsHash (readonly)

Returns the options hash determined by the command-line option parser.

Returns:

  • (Hash)

    the options hash determined by the command-line option parser



8
9
10
# File 'lib/pocketwatch/watcher.rb', line 8

def options
  @options
end

Instance Method Details

#runvoid

This method returns an undefined value.

Begin the watcher task, executing the provided command in a loop. The loop will only break when interrupted in the shell.



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/pocketwatch/watcher.rb', line 27

def run
  loop do
    # Double buffer the output by precomputing the results of the system
    # call. Then, clear the terminal and print the results as quickly as
    # possible - this should avoid any flickering due to clearing the
    # terminal. Restrict the output of the command to the current height of
    # the terminal - scrolling is not supported, and we want to see the
    # first part of the output, not the last.
    num_lines = `tput lines`.strip.to_i - 1
    num_lines = 1 unless num_lines.positive?
    output = `#{@command}`.split("\n").first(num_lines)

    clear_screen
    puts output

    sleep(@options[:interval] || 2)
  end
rescue Errno::EPIPE, SystemExit, Interrupt
  clear_screen
  exit 0
end