Class: Blackbook::Importer::Csv

Inherits:
Base
  • Object
show all
Defined in:
lib/blackbook/importer/csv.rb

Overview

Imports contacts from a CSV file

Constant Summary collapse

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

Instance Attribute Summary

Attributes inherited from Base

#options

Instance Method Summary collapse

Methods inherited from Base

#import, #service_name

Instance Method Details

#=~(options) ⇒ Object

Matches this importer to a file that contains CSV values



13
14
15
# File 'lib/blackbook/importer/csv.rb', line 13

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

#fetch_contacts!Object

fetch_contacts! implementation for this importer



20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/blackbook/importer/csv.rb', line 20

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

#to_columns(line) ⇒ Object

:nodoc:



44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/blackbook/importer/csv.rb', line 44

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

#to_hash(cols, vals) ⇒ Object

:nodoc:



36
37
38
39
40
41
42
# File 'lib/blackbook/importer/csv.rb', line 36

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