Sha256: c6002185a72691013c7f2d663acb160aff0b8da03ff436702c760a8a28a7ee23

Contents?: true

Size: 790 Bytes

Versions: 1

Compression:

Stored size: 790 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

1 entries across 1 versions & 1 rubygems

Version Path
metacrunch-2.1.1 lib/metacrunch/file_writer.rb