Sha256: 3da67a7283b5e9d2a467155ea4a2de1ccc884c7c871de761256deb8f035c1586

Contents?: true

Size: 1.85 KB

Versions: 110

Compression:

Stored size: 1.85 KB

Contents

module TSV
  class Dumper
    attr_accessor :in_stream, :stream, :options, :filename, :sep
    def self.stream(options = {}, filename = nil, &block)
      dumper = TSV::Dumper.new options, filename
      Thread.new(Thread.current) do |parent|
        yield dumper
        dumper.close
      end
      dumper.stream
    end

    def initialize(options, filename = nil)
      if TSV  === options
        @options = options.options.merge(:key_field => options.key_field, :fields => options.fields)
        @filename ||= options.filename
      else
        @options = options
        @filename = filename
      end
      @filename ||= Misc.fingerprint options
      @stream, @in_stream = Misc.pipe
    end

    def self.values_to_s(values, fields = nil, sep = "\t")
      sep = "\t" if sep.nil?
      case values
      when nil
        if fields.nil? or fields.empty?
          "\n"
        else
          sep + ([""] * fields.length) * sep << "\n"
        end
      when Array
        sep + (values.collect{|v| Array === v ? v * "|" : v} * sep) << "\n"
      else
        sep + values.to_s << "\n"
      end
    end

    def init
      options = @options.dup
      key_field, fields = Misc.process_options options, :key_field, :fields

      str = TSV.header_lines(key_field, fields, options)

      Thread.pass while IO.select(nil, [@in_stream],nil,1).nil?

      @in_stream.puts str
    end

    def add(k,v)
      @fields ||= @options[:fields]
      @sep ||= @options[:sep]
      begin
        Thread.pass while IO.select(nil, [@in_stream],nil,1).nil?
        @in_stream << k << TSV::Dumper.values_to_s(v, @fields, @sep)
      rescue IOError
      rescue Exception
        raise $!
      end
    end

    def close_out
      @stream.close unless @stream.closed?
    end

    def close_in
      @in_stream.close unless @in_stream.closed?
    end

    def close
      close_in
    end
  end
end

Version data entries

110 entries across 110 versions & 1 rubygems

Version Path
rbbt-util-5.19.16 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.15 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.14 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.13 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.12 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.11 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.10 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.9 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.8 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.7 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.6 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.5 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.4 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.3 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.2 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.1 lib/rbbt/tsv/dumper.rb
rbbt-util-5.19.0 lib/rbbt/tsv/dumper.rb
rbbt-util-5.18.1 lib/rbbt/tsv/dumper.rb
rbbt-util-5.18.0 lib/rbbt/tsv/dumper.rb
rbbt-util-5.17.89 lib/rbbt/tsv/dumper.rb