Module: Gorillib::Model::LoadFromCsv::ClassMethods
- Defined in:
- lib/gorillib/model/serialization/csv.rb
Instance Method Summary collapse
-
#each_in_csv(filename, options = {}) { ... } ⇒ Object
Iterate a block over each line of a CSV file.
-
#load_csv(*args) ⇒ Object
With a block, calls block on each object in turn (and returns nil).
Instance Method Details
#each_in_csv(filename, options = {}) { ... } ⇒ Object
Iterate a block over each line of a CSV file
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, ={}) filename = Pathname.path_to(filename) = .merge() # pop_headers = .delete(:pop_headers) num_fields = .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 [:headers] # CSV.open(filename, ) 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.
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 |