Module: CSVHandlers

Included in:
CrossRef, DuckScraper, LinScraper, Linsc, Merger
Defined in:
lib/linsc/csv_handlers.rb

Instance Method Summary collapse

Instance Method Details

#append_to_csv(file, row) ⇒ Object



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/linsc/csv_handlers.rb', line 14

def append_to_csv(file, row)
  tries = 10
  begin
    f = CSV.open(file, "a+", headers: row.headers, force_quotes: true)
    f << row
    f.close
  rescue
    tries -= 1
    if tries > 0
      retry
    else
      puts "Unable to write to file #{file}"
      puts "Make sure the file exists and is not open in any other programs and try again. If that does not work try restarting your computer, or restarting the project with the -r flag."
      exit
    end
  end
end

#create_file(f) ⇒ Object



32
33
34
35
36
37
38
39
# File 'lib/linsc/csv_handlers.rb', line 32

def create_file(f)
  unless File.exist?(f)
    FileUtils.touch(f)
    csv = CSV.open(f, "w+")
    csv << @headers.collect {|x| x && x.encode('utf-8')}
    csv.close
  end
end

#create_file_with_headers(f, headers) ⇒ Object



41
42
43
44
45
46
47
48
# File 'lib/linsc/csv_handlers.rb', line 41

def create_file_with_headers(f, headers)
  unless File.exist?(f)
    FileUtils.touch(f)
    csv = CSV.open(f, "w+")
    csv << headers.collect {|x| x && x.encode('utf-8')}
    csv.close
  end
end

#create_row(row, headers, encoding = nil) ⇒ Object



2
3
4
5
6
7
8
9
10
11
12
# File 'lib/linsc/csv_handlers.rb', line 2

def create_row(row, headers, encoding = nil)
  values = []
  headers.each do |header|
    if encoding
      values << row[header].encode(encoding) if row[header]
    else
      values << row[header]
    end
  end
  CSV::Row.new(headers, values)
end

#get_headers(file) ⇒ Object



50
51
52
# File 'lib/linsc/csv_handlers.rb', line 50

def get_headers(file)
  CSV.open(file, headers: true, return_headers: true).shift.headers
end