Sha256: 62555c3ce2aae5e2308c84f019f6b96c17b2351926b04d24602a7cac24b2cb2f

Contents?: true

Size: 1.3 KB

Versions: 10

Compression:

Stored size: 1.3 KB

Contents

require 'fastercsv'

##
# Imports contacts from a CSV file

class Blackbook::Importer::Csv < Blackbook::Importer::Base

  DEFAULT_COLUMNS = [:name,:email,:misc]

  ##
  # Matches this importer to a file that contains CSV values

  def =~(options)
    options && options[:file].respond_to?(:open) ? true : false
  end

  ##
  # fetch_contacts! implementation for this importer

  def fetch_contacts!
    lines = IO.readlines(options[:file].path)
    columns = to_columns(lines.first)
    lines.shift if columns.first == :name
    columns = DEFAULT_COLUMNS.dup unless columns.first == :name

    contacts = Array.new
    lines.each do |l|
      vals = l.split(',')
      next if vals.empty?
      contacts << to_hash(columns, vals)
    end

    contacts
  end

  def to_hash(cols, vals) # :nodoc:
    h = Hash.new
    cols.each do |c|
      h[c] = (c == cols.last) ? vals.join(',') : vals.shift
    end
    h
  end

  def to_columns(line) # :nodoc:
    columns = Array.new
    tags = line.split(',')
    # deal with "Name,E-mail..." oddity up front
    if tags.first =~ /^name$/i
      tags.shift
      columns << :name
      if tags.first =~ /^e.?mail/i # E-mail or Email
        tags.shift
        columns << :email
      end
    end
    tags.each{|v| columns << v.strip.to_sym}
    columns
  end

  Blackbook.register(:csv, self)
end

Version data entries

10 entries across 10 versions & 2 rubygems

Version Path
bcardarella-blackbook-1.0.10 lib/blackbook/importer/csv.rb
bcardarella-blackbook-1.0.11 lib/blackbook/importer/csv.rb
bcardarella-blackbook-1.0.7 lib/blackbook/importer/csv.rb
bcardarella-blackbook-1.0.8 lib/blackbook/importer/csv.rb
bcardarella-blackbook-1.0.9 lib/blackbook/importer/csv.rb
blackbook-1.0.3 lib/blackbook/importer/csv.rb
blackbook-1.0.2 lib/blackbook/importer/csv.rb
blackbook-1.0.0 lib/blackbook/importer/csv.rb
blackbook-1.0.1 lib/blackbook/importer/csv.rb
blackbook-1.0.4 lib/blackbook/importer/csv.rb