Class: NotifiedTail

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

Overview

Tail lines in a given file Inspired by rubyforadmins.com/reading-growing-files

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#file_pathObject (readonly)

Returns the value of attribute file_path.



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

def file_path
  @file_path
end

Class Method Details

.tail(file_path, opts = {}, &on_line) ⇒ Object

Yields complete lines, one at a time. Works even if file doesn’t exist yet.

Parameters:

  • file_path (String)

    The file to tail

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

    a customizable set of options

Options Hash (opts):

  • seek_end (Boolean) — default: true

    If true, seeks to the end of the file before reporting lines. Otherwise, reports all lines starting at the beginning of the file.

  • force_poll (Boolean) — default: false

    Poll even if inotify or kqueue are available



15
16
17
# File 'lib/notified_tail.rb', line 15

def self.tail(file_path, opts={}, &on_line)
  new.tail(file_path, opts, &on_line)
end

Instance Method Details

#stopObject



36
37
38
39
40
# File 'lib/notified_tail.rb', line 36

def stop
  @queue.stop if @queue
  @queue = nil
  @stopped = true
end

#tail(file_path, opts = {}, &on_line) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/notified_tail.rb', line 19

def tail(file_path, opts={}, &on_line)
  @file_path = file_path
  @stopped = false
  seek_end = opts.fetch(:seek_end, true)
  @force_poll = opts.fetch(:force_poll, false)
  sleep(0.25) until File.exists?(file_path)
  File.open(file_path) do |file|
    unreported_line = ''
    if seek_end
      file.seek(0, IO::SEEK_END)
    else
      read_and_report_lines(file, unreported_line, &on_line)
    end
    when_modified(file_path) { read_and_report_lines(file, unreported_line, &on_line) }
  end
end