Class: Pants::Writers::FileWriter

Inherits:
BaseWriter show all
Includes:
LogSwitch::Mixin
Defined in:
lib/pants/writers/file_writer.rb

Overview

This is the interface for FileWriterConnections. It controls starting, stopping, and threading the connection.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from BaseWriter

#running?, #starter, #stopper, #write_object

Constructor Details

#initialize(file_path, read_from_channel) ⇒ FileWriter

Returns a new instance of FileWriter.

Parameters:

  • read_from_channel (EventMachine::Channel)

    The channel to read data from and thus write to file.

  • file_path (String)

    The path to write to.



19
20
21
22
23
24
25
# File 'lib/pants/writers/file_writer.rb', line 19

def initialize(file_path, read_from_channel)
  @file = file_path.is_a?(File) ? file_path : File.open(file_path, 'w')
  @file_path = file_path
  @write_object = @file_path

  super(read_from_channel)
end

Instance Attribute Details

#file_pathString (readonly)

Returns The path to the file that’s being written to.

Returns:

  • (String)

    The path to the file that’s being written to.



13
14
15
# File 'lib/pants/writers/file_writer.rb', line 13

def file_path
  @file_path
end

Instance Method Details

#startObject



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/pants/writers/file_writer.rb', line 33

def start
  log "#{__id__} Adding a #{self.class} to write to #{@file_path}"

  EM.defer do
    @read_from_channel.subscribe do |data|
      begin
        bytes_written = @file.write_nonblock(data)
        log "Wrote normal, #{bytes_written} bytes"
      rescue IOError
        log "Finishing writing; only wrote #{bytes_written}"

        unless bytes_written == data.size
          File.open(@file, 'a') do |file|
            file.write_nonblock(data)
          end
        end
      end
    end

    start_loop = EM.tick_loop { :stop unless @file.closed? }
    start_loop.on_stop { starter.call }
  end
end

#stopObject



27
28
29
30
31
# File 'lib/pants/writers/file_writer.rb', line 27

def stop
  log "Finishing ID #{__id__} and closing file #{@file}"
  @file.close unless @file.closed?
  stopper.call
end