Class: Britebox::ExportBuffer

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

Instance Method Summary collapse

Constructor Details

#initialize(out_file_name, header_line, col_separator) ⇒ ExportBuffer

Returns a new instance of ExportBuffer.



3
4
5
6
7
8
9
10
11
12
# File 'lib/britebox/export_buffer.rb', line 3

def initialize(out_file_name, header_line, col_separator)
  @file = File.new out_file_name, 'w+'
  @col_separator = col_separator
  write_header_row(header_line)
  @last_exported_line_idx = 0

  @buffer = []
  @backlog = []
  @semaphore = Mutex.new
end

Instance Method Details

#buffer_sizeObject



14
15
16
# File 'lib/britebox/export_buffer.rb', line 14

def buffer_size
  100
end

#closeObject



53
54
55
# File 'lib/britebox/export_buffer.rb', line 53

def close
  @file.close
end

#flush_backlogObject



34
35
36
37
38
39
40
41
42
# File 'lib/britebox/export_buffer.rb', line 34

def flush_backlog
  @semaphore.synchronize do
    @backlog.each do |item|
      @buffer << item[:line]
      @last_exported_line_idx += 1
    end
  end
  flush_buffer(true)
end

#flush_buffer(force = false) ⇒ Object



44
45
46
47
48
49
50
51
# File 'lib/britebox/export_buffer.rb', line 44

def flush_buffer(force = false)
  if force || @buffer.size > buffer_size
    @semaphore.synchronize do
      @file.write @buffer.map{ |line| CSV.generate_line(line, col_sep: @col_separator) }.join
      @buffer = []
    end
  end
end

#push(item) ⇒ Object Also known as: <<

N, line: […]



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

def push(item)
  check_backlog

  @semaphore.synchronize do
    if item[:n] == @last_exported_line_idx
      @buffer << item[:line]
      @last_exported_line_idx += 1
    else
      @backlog << item
    end
  end

  flush_buffer
end

#statusObject



57
58
59
60
61
62
63
# File 'lib/britebox/export_buffer.rb', line 57

def status
  {
    buffer: @buffer.size,
    backlog: @backlog.size,
    last_exported_line_idx: @last_exported_line_idx,
  }
end