Class: Bcat::Reader

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

Overview

ARGF style multi-file streaming interface. Input is read with IO#readpartial to avoid buffering.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(is_command, args = []) ⇒ Reader

Returns a new instance of Reader.



11
12
13
14
# File 'lib/bcat/reader.rb', line 11

def initialize(is_command, args=[])
  @is_command = is_command
  @args = args
end

Instance Attribute Details

#argsObject (readonly)

Returns the value of attribute args.



8
9
10
# File 'lib/bcat/reader.rb', line 8

def args
  @args
end

#fdsObject (readonly)

Returns the value of attribute fds.



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

def fds
  @fds
end

#is_commandObject (readonly)

Returns the value of attribute is_command.



7
8
9
# File 'lib/bcat/reader.rb', line 7

def is_command
  @is_command
end

Instance Method Details

#eachObject



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/bcat/reader.rb', line 35

def each
  yield @buf.shift while @buf.any?
  while fd = fds.first
    fds.shift and next if fd.closed?
    fd.sync = true
    begin
      while buf = fd.readpartial(4096)
        yield buf
      end
    rescue EOFError
      fd.close
    end
    fds.shift
  end
end

#openObject



16
17
18
19
# File 'lib/bcat/reader.rb', line 16

def open
  @fds = is_command ? open_command : open_files
  @buf = []
end

#open_commandObject



21
22
23
# File 'lib/bcat/reader.rb', line 21

def open_command
  [IO.popen(args.join(' '), 'rb')]
end

#open_filesObject



25
26
27
28
29
30
31
32
33
# File 'lib/bcat/reader.rb', line 25

def open_files
  args.map do |f|
    if f == '-'
      $stdin
    else
      File.open(f, 'rb')
    end
  end
end

#sniffObject



51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# File 'lib/bcat/reader.rb', line 51

def sniff
  @format ||=
    catch :detect do
      each do |chunk|
        @buf << chunk
        case chunk
        when /\A\s*</m
          throw :detect, 'html'
        when /\A\s*[^<]/m
          throw :detect, 'text'
        end
      end
      throw :detect, 'text'
    end
end