Module: Gorillib::Model::LoadFromCsv::ClassMethods

Defined in:
lib/gorillib/model/serialization/csv.rb

Instance Method Summary collapse

Instance Method Details

#each_in_csv(filename, options = {}) { ... } ⇒ Object

Iterate a block over each line of a CSV file

Yields:

  • an object instantiated from each line in the file.

Raises:



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/gorillib/model/serialization/csv.rb', line 22

def each_in_csv(filename, options={})
  filename = Pathname.path_to(filename)
  options = csv_options.merge(options)
  #
  pop_headers = options.delete(:pop_headers)
  num_fields  = options.delete(:num_fields){ (fields.length .. fields.length) }
  raise ArgumentError, "The :headers option to CSV changes its internal behavior; use 'pop_headers: true' to ignore the first line" if options[:headers]
  #
  CSV.open(filename, options) do |csv_file|
    csv_file.shift if pop_headers
    csv_file.each do |tuple|
      next if tuple.empty?
      unless num_fields.include?(tuple.length) then raise Gorillib::Model::RawDataMismatchError, "yark, spurious fields: #{tuple.inspect}" ; end
      yield from_tuple(*tuple)
    end
    nil
  end
end

#load_csv(*args) ⇒ Object

With a block, calls block on each object in turn (and returns nil)

With no block, accumulates all the instances into the array it returns. As opposed to the with-a-block case, the memory footprint of this increases as the filesize does, so use caution with large files.

Returns:

  • with a block, returns nil; with no block, an array of this class' instances



48
49
50
51
52
53
54
55
56
# File 'lib/gorillib/model/serialization/csv.rb', line 48

def load_csv(*args)
  if block_given?
    each_in_csv(*args, &Proc.new)
  else
    objs = []
    each_in_csv(*args){|obj| objs << obj }
    objs
  end
end