Class: ExtraLoop::CsvExtractor

Inherits:
ExtractorBase show all
Defined in:
lib/extraloop/csv_extractor.rb

Instance Attribute Summary

Attributes inherited from ExtractorBase

#field_name

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ CsvExtractor

Returns a new instance of CsvExtractor.



3
4
5
6
# File 'lib/extraloop/csv_extractor.rb', line 3

def initialize(*args)
  super(*args)
  @selector = args[2] if args[2] && args[2].is_a?(Integer)
end

Instance Method Details

#extract_field(row, record = nil) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/extraloop/csv_extractor.rb', line 8

def extract_field(row, record=nil)
  target = row = row.respond_to?(:entries)? row : parse(row)
  headers = @environment.document.first
  selector = !@selector && @field_name || @selector

  # allow using CSV column names or array indices as selectors
  target = row[headers.index(selector.to_s)] if selector && selector.to_s.match(/[a-z]/i)
  target = row[selector] if selector.is_a?(Integer)

  target = @environment.run(target, record, &@callback) if @callback
  target
end

#extract_list(input) ⇒ Object



21
22
23
24
# File 'lib/extraloop/csv_extractor.rb', line 21

def extract_list(input)
  rows = (input.respond_to?(:entries) ? input : parse(input))
  Array(@callback && @environment.run(rows, &@callback) || rows)
end

#parse(input, options = Hash.new) ⇒ Object



27
28
29
30
31
# File 'lib/extraloop/csv_extractor.rb', line 27

def parse(input, options=Hash.new)
  super(input)
  document = CSV.parse(input, options)
  @environment.document = document
end