Class: Segua

Inherits:
Object
  • Object
show all
Defined in:
lib/segua.rb,
lib/segua/version.rb

Overview

Segua tracks changes in files in @dir, always following the most recently changed.

It emulates tail -f. tail's argument, -f, stands for "follow." "Segua" is the imperative form of "to follow" in Italian.

Constant Summary collapse

Version =

Gem version

"0.1.1"

Instance Method Summary collapse

Constructor Details

#initialize(dir) ⇒ Segua

Create a new Segua against dir.



9
10
11
# File 'lib/segua.rb', line 9

def initialize(dir)
  @dir = dir
end

Instance Method Details

#followObject

Following the file with the most recent modification time, print each line of the file, indefinitely.



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/segua.rb', line 24

def follow
  file_name = latest_file
  while file_name.nil?
    sleep 1
    file_name = latest_file
  end

  print_file_update(file_name)
  handle = File.open file_name

  while true
    line = handle.gets
    if line.nil?
      sleep 0.5
    else
      puts line.chomp.strip
    end
    new_file_name = latest_file
    while new_file_name.nil?
      sleep 1
      new_file_name = latest_file
    end
    if new_file_name != file_name
      print_file_update(new_file_name)
      file_name = new_file_name
      handle.close
      handle = File.open file_name
      next
    end
  end
  handle.close
end

#latest_fileObject

Find, among all of the files located directly inside dir, the one with the most recent modification time. Returns the full file path as a String.



59
60
61
62
63
# File 'lib/segua.rb', line 59

def latest_file
  Dir.entries(@dir).map {|f| File.join(@dir, f) }.reject {|f| File.directory?(f) }.inject do |memo,file|
  File.mtime(memo) > File.mtime(file) ? memo : file
  end
end

Print a few lines before switching to a new file, indicating the new file.



14
15
16
17
18
19
20
# File 'lib/segua.rb', line 14

def print_file_update(file_name)
  puts ""
  puts "SEGUA: ==================" + ('='*file_name.length)
  puts "SEGUA: most recent file: #{file_name}"
  puts "SEGUA: ==================" + ('='*file_name.length)
  puts ""
end