Sha256: 666720521d9789a339b4893f05f859c2b9b431da168dcd9c9c32e430a89a3299

Contents?: true

Size: 796 Bytes

Versions: 4

Compression:

Stored size: 796 Bytes

Contents

module Metacrunch
  class FileWriter

    class FileExistError < RuntimeError ; end


    def initialize(filename, override: false, compress: nil)
      @path       = ::File.expand_path(filename)
      @compressed = (compress ||= @path.ends_with?(".gz"))

      if ::File.exist?(@path) && !override
        raise FileExistError, "File #{@path} already exists. Set override = true to override the existing file."
      end
    end

    def write(data, options = {})
      if block_given?
        yield(io)
      else
        io.write(data)
      end
    end

    def flush
      @io.flush if @io
    end

    def close
      flush
      @io.close if @io
    end

  private

    def io
      @io ||= (@compressed == true) ? Zlib::GzipWriter.open(@path) : ::File.open(@path, "w")
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
metacrunch-2.2.3 lib/metacrunch/file_writer.rb
metacrunch-2.2.2 lib/metacrunch/file_writer.rb
metacrunch-2.2.1 lib/metacrunch/file_writer.rb
metacrunch-2.2.0 lib/metacrunch/file_writer.rb