Class: Drudgery::Loaders::CSVLoader

Inherits:
Object
  • Object
show all
Defined in:
lib/drudgery/loaders/csv_loader.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filepath, options = {}) ⇒ CSVLoader

Returns a new instance of CSVLoader.



6
7
8
9
10
11
12
13
# File 'lib/drudgery/loaders/csv_loader.rb', line 6

def initialize(filepath, options={})
  @filepath = filepath
  @options = options

  @write_headers = true

  @name = "csv:#{File.basename(@filepath)}"
end

Instance Attribute Details

#nameObject (readonly)

Returns the value of attribute name.



4
5
6
# File 'lib/drudgery/loaders/csv_loader.rb', line 4

def name
  @name
end

Instance Method Details

#col_sepObject



15
16
17
# File 'lib/drudgery/loaders/csv_loader.rb', line 15

def col_sep
  @options[:col_sep]
end

#col_sep=(char) ⇒ Object



19
20
21
# File 'lib/drudgery/loaders/csv_loader.rb', line 19

def col_sep=(char)
  @options[:col_sep] = char
end

#load(records) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/drudgery/loaders/csv_loader.rb', line 23

def load(records)
  columns = records.first.keys.sort { |a,b| a.to_s <=> b.to_s }

  CSV.open(@filepath, 'a', @options) do |csv|
    if @write_headers
      csv << columns
      @write_headers = false
    end

    records.each do |record|
      csv << columns.map { |column| record[column] }
    end
  end
end