Class: Cardigan::Command::ImportCards

Inherits:
Object
  • Object
show all
Defined in:
lib/cardigan/command/import_cards.rb

Instance Method Summary collapse

Constructor Details

#initialize(repository, io) ⇒ ImportCards

Returns a new instance of ImportCards.



4
5
6
# File 'lib/cardigan/command/import_cards.rb', line 4

def initialize repository, io
  @repository, @io = repository, io
end

Instance Method Details

#execute(filename) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/cardigan/command/import_cards.rb', line 8

def execute filename
  filename += ".csv"
  unless File.exist?(filename)
    @io.say "#{filename} does not exist"
    return
  end
  header, id_index = nil, nil
  CSV.open(filename, 'r') do |row|
    if header
      card = @repository.load(row[id_index]) if id_index and row[id_index]
      @io.say card ? "updating #{card['id']}" : "creating new card"
      card = @repository.create unless card
      editor = Cardigan::CardEditor.new(card, @io)
      header.each_with_index do |field, index|
        editor.set field, row[index]
      end
      @repository.save card
    else
      header = row
      id_index = header.find_index('id')
    end
  end
end