Module: StructuredCsv::CsvJoin

Defined in:
lib/structured_csv/csv_join.rb

Class Method Summary collapse

Class Method Details

.convert(csvdir, outfile) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/structured_csv/csv_join.rb', line 31

def self.convert(csvdir, outfile)
  raise "first argument must be a directory!" unless File.directory?(csvdir)

  csv = CSV.open(outfile, "wb", encoding: "UTF-8")

  csvfiles = Dir.glob(File.join(csvdir, "**", "*.csv")).sort
  raise "directory must contain .csv files!" if csvfiles.empty?

  # Assume all files use the same header structure as the first CSV file
  header    = []
  csvheader = ""

  csvfiles.each do |csvfile|
    content = StructuredCsv::Common.load_csv(csvfile)

    csvheader = content.shift
    if header.empty?
      header = ["name"] + csvheader
      csv << header
    end

    basename = Pathname.new(csvfile).basename.sub_ext("").to_s
    content.each do |filerow|
      row = []
      filerow.each do |value|
        row << case value
               when String
                 value.strip
               else
                 value
               end
      end

      all_empty = row.all? do |f|
        f.nil? || f.empty?
      end
      next if all_empty

      row.unshift(basename)

      csv << row
    end
  end

  csv.close
end

.join(csv, section_name) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/structured_csv/csv_join.rb', line 7

def self.join(csv, section_name)
  first_row = nil
  last_row  = -1

  warn "section_name #{section_name}"

  csv.each_with_index do |row, index|
    if first_row.nil? && Csv2Yaml.is_start_of_portion?(row, section_name)
      warn "found first"
      first_row = index + 1
      next
    end

    next unless !first_row.nil? && Csv2Yaml.is_row_empty?(row)

    warn "found last"
    last_row = index
    break
  end

  warn "first #{first_row}  last #{last_row}"
  csv[first_row..last_row]
end