Sha256: aca6099b46915e2b622575d3f1aa392f126549b0f3eef07f606a2951c6b11b40

Contents?: true

Size: 1013 Bytes

Versions: 7

Compression:

Stored size: 1013 Bytes

Contents

require 'csv'

module Sources
  
  # Describes a CSV source, a file with csv in it.
  # Give it a sequence of field names and a file option with the filename.
  #
  class NoCSVFileGiven < StandardError; end
  
  class CSV < Base
    
    attr_reader :file_name, :field_names
    
    def initialize *field_names, options
      @field_names = field_names
      @file_name   = Hash === options && options[:file] || raise_no_file_given(field_names)
    end
    
    #
    #
    def raise_no_file_given field_names
      raise NoCSVFileGiven.new field_names.join(', ')
    end
    
    # Harvests the data to index.
    #
    def harvest _, field
      index = field_names.index field.name
      get_data do |ary|
        indexed_id = ary.shift.to_i
        text       = ary[index]
        next unless text
        text.force_encoding 'utf-8' # TODO Still needed?
        yield indexed_id, text
      end
    end
    
    #
    #
    def get_data &block
      ::CSV.foreach file_name, &block
    end
    
  end
  
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
picky-0.3.0 lib/picky/sources/csv.rb
picky-0.2.4 lib/picky/sources/csv.rb
picky-0.2.3 lib/picky/sources/csv.rb
picky-0.2.2 lib/picky/sources/csv.rb
picky-0.2.1 lib/picky/sources/csv.rb
picky-0.2.0 lib/picky/sources/csv.rb
picky-0.1.0 lib/picky/sources/csv.rb