Sha256: 65e5548d12f48272c13962d36506ce4aae7badcb459ac615df9cc9e6367852e2

Contents?: true

Size: 1.79 KB

Versions: 63

Compression:

Stored size: 1.79 KB

Contents

require 'csv'

module TSV
  def self.csv(obj, options = {}) 
    options = Misc.add_defaults IndiferentHash.setup(options.dup), :headers => true, :type => :list
    headers = options[:headers]

    noheaders = ! headers

    type = options.delete :type
    merge = options.delete :merge
    key_field = options.delete :key_field
    fields = options.delete :fields
    
    if key_field || fields
      orig_type = type
      type = :double
      merge = true
    end

    options[:headers] = false

    csv = case obj
          when Path
            CSV.read obj.find.open, options
          when String
            if Misc.is_filename?(obj)
              CSV.read obj, options
            else
              CSV.new obj, options
            end
          else
            CSV.new obj, options
          end

    tsv = if noheaders
            TSV.setup({}, :key_field => nil, :fields => nil, :type => type)
          else
            key, *csv_fields = csv.shift
            TSV.setup({}, :key_field => key, :fields => csv_fields, :type => type)
          end

    csv.each_with_index do |row,i|
      if noheaders
        key, values = ["row-#{i}", row]
      else
        key, *values = row
      end

      case type
      when :double, :flat
        tsv.zip_new(key, values)
      when :single
        tsv[key] = values.first
      when :list
        tsv[key] = values
      end
    end

    if key_field || fields
      tsv = tsv.reorder(key_field, fields, :zipped => true, :merge => true)
      if tsv.type != orig_type
        tsv = case orig_type
              when :list
                tsv.to_list
              when :single
                tsv.to_single
              when :list
                tsv.to_list
              when :flat
                tsv.to_flat
              end
      end
    end

    tsv
  end
end

Version data entries

63 entries across 63 versions & 1 rubygems

Version Path
rbbt-util-5.30.9 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.8 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.7 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.6 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.5 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.4 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.3 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.2 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.1 lib/rbbt/tsv/csv.rb
rbbt-util-5.30.0 lib/rbbt/tsv/csv.rb
rbbt-util-5.29.4 lib/rbbt/tsv/csv.rb
rbbt-util-5.29.2 lib/rbbt/tsv/csv.rb
rbbt-util-5.29.1 lib/rbbt/tsv/csv.rb
rbbt-util-5.29.0 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.14 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.12 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.11 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.10 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.9 lib/rbbt/tsv/csv.rb
rbbt-util-5.28.8 lib/rbbt/tsv/csv.rb