Class: Onlylogs::File

Inherits:
Object
  • Object
show all
Defined in:
app/models/onlylogs/file.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, last_position: 0) ⇒ File

Returns a new instance of File.



7
8
9
10
11
# File 'app/models/onlylogs/file.rb', line 7

def initialize(path, last_position: 0)
  self.path = path
  self.last_position = last_position
  validate!
end

Instance Attribute Details

#last_positionObject

Returns the value of attribute last_position.



5
6
7
# File 'app/models/onlylogs/file.rb', line 5

def last_position
  @last_position
end

#pathObject

Returns the value of attribute path.



5
6
7
# File 'app/models/onlylogs/file.rb', line 5

def path
  @path
end

Class Method Details

.text_file?(path) ⇒ Boolean

Returns:

  • (Boolean)


44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'app/models/onlylogs/file.rb', line 44

def self.text_file?(path)
  return false unless ::File.exist?(path)
  return false if ::File.zero?(path)

  # Read first chunk and check for null bytes (binary indicator)
  ::File.open(path, "rb") do |file|
    chunk = file.read(8192) || ""
    # If it contains null bytes, it's likely binary
    return false if chunk.include?("\x00")
  end

  true
end

Instance Method Details

#exist?Boolean

Returns:

  • (Boolean)


36
37
38
# File 'app/models/onlylogs/file.rb', line 36

def exist?
  ::File.exist?(path)
end

#go_to_position(position) ⇒ Object



13
14
15
16
17
# File 'app/models/onlylogs/file.rb', line 13

def go_to_position(position)
  return if position < 0

  self.last_position = position
end

#grep(filter, regexp_mode: false, start_position: 0, end_position: nil, &block) ⇒ Object



58
59
60
61
62
# File 'app/models/onlylogs/file.rb', line 58

def grep(filter, regexp_mode: false, start_position: 0, end_position: nil, &block)
  Grep.grep(filter, path, regexp_mode: regexp_mode, start_position: start_position, end_position: end_position) do |content|
    yield content
  end
end

#sizeObject



32
33
34
# File 'app/models/onlylogs/file.rb', line 32

def size
  ::File.size(path)
end

#text_file?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'app/models/onlylogs/file.rb', line 40

def text_file?
  self.class.text_file?(path)
end

#watch(&block) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'app/models/onlylogs/file.rb', line 19

def watch(&block)
  # return enum_for(:watch) unless block

  loop do
    sleep 0.5

    new_lines = read_new_lines
    next if new_lines.empty?

    yield new_lines
  end
end