Class: Importer::CsvReader

Inherits:
DataReader show all
Defined in:
lib/iron/import/csv_reader.rb

Instance Attribute Summary

Attributes inherited from DataReader

#format

Instance Method Summary collapse

Methods inherited from DataReader

#add_error, #add_exception, for_format, for_path, for_source, for_stream, is_stream?, #load, #load_each, #parse_value, path_from_stream, #supports?, #supports_file!, #supports_file?, #supports_stream!, #supports_stream?, verify_nokogiri!, verify_roo!

Constructor Details

#initialize(importer) ⇒ CsvReader

Returns a new instance of CsvReader.



7
8
9
10
11
# File 'lib/iron/import/csv_reader.rb', line 7

def initialize(importer)
  super(importer, :csv)
  supports_file!
  supports_stream!
end

Instance Method Details

#init_source(mode, source) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
# File 'lib/iron/import/csv_reader.rb', line 13

def init_source(mode, source)
  if mode == :stream
    # For streams, we just read 'em in and parse 'em
    text = source.read
    
  elsif mode == :file
    # Files have a different path
    text = File.read(source)
    
  else
    # WTF?
    @importer.add_error("Unsupported CSV mode: #{mode.inspect}")
    return false
  end

  # Fix shitty Windows line-feeds so things are standardized
  text.gsub!(/\r\n/, "\n")
  text.gsub!(/\r/, "\n")

  # Look at first line, count sep chars, pick the most common
  sep_char = ','
  line = text.split(/\n/, 2).first
  if line.count("\t") > line.count(',')
    sep_char = "\t"
  end

  # Parse it out
  encoding = @importer.encoding || 'UTF-8'
  options = {
    :encoding => "#{encoding}:UTF-8",
    :skip_blanks => true,
    :col_sep => sep_char
  }
  begin
    @raw_rows = CSV.parse(text, options)
  rescue Exception => e
    @importer.add_error('Error encountered while parsing CSV')
    @importer.add_exception(e)
    return false
  end

  if @raw_rows.nil? || @raw_rows.count == 0
    @importer.add_error('No rows found - unable to process CSV file')
    return false
  else
    return true
  end
end

#load_raw(scopes, &block) ⇒ Object



62
63
64
65
66
# File 'lib/iron/import/csv_reader.rb', line 62

def load_raw(scopes, &block)
  # Normally, we'd check the scopes and return the proper data, but for CSV files, 
  # there's only one scope...
  block.call(@raw_rows)
end