Sha256: 860c4a4cea87748581fa43dd0a39e92e7b598aac6d7095cc3d4e1a8e0d694370

Contents?: true

Size: 1.05 KB

Versions: 2

Compression:

Stored size: 1.05 KB

Contents

module Sources
  
  # Describes a CSV source, a file with csv in it.
  # Give it a sequence of category names and a file option with the filename.
  #
  class NoCSVFileGiven < StandardError; end
  
  class CSV < Base
    
    attr_reader :file_name, :category_names
    
    def initialize *category_names, options
      require 'csv'
      @category_names = category_names
      @file_name   = Hash === options && options[:file] || raise_no_file_given(category_names)
    end
    
    #
    #
    def raise_no_file_given category_names
      raise NoCSVFileGiven.new(category_names.join(', '))
    end
    
    # Harvests the data to index.
    #
    def harvest _, category
      index = category_names.index category.name
      get_data do |ary|
        indexed_id = ary.shift.to_i # TODO is to_i necessary?
        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

2 entries across 2 versions & 1 rubygems

Version Path
picky-0.12.1 lib/picky/sources/csv.rb
picky-0.12.0 lib/picky/sources/csv.rb