Class: Cardigan::Command::ImportCards
- Inherits:
-
Object
- Object
- Cardigan::Command::ImportCards
- Defined in:
- lib/cardigan/command/import_cards.rb
Instance Attribute Summary collapse
-
#help ⇒ Object
readonly
Returns the value of attribute help.
-
#usage ⇒ Object
readonly
Returns the value of attribute usage.
Instance Method Summary collapse
- #execute(filename) ⇒ Object
-
#initialize(repository, io) ⇒ ImportCards
constructor
A new instance of ImportCards.
Constructor Details
#initialize(repository, io) ⇒ ImportCards
Returns a new instance of ImportCards.
8 9 10 11 12 |
# File 'lib/cardigan/command/import_cards.rb', line 8 def initialize repository, io @repository, @io = repository, io @usage = '<filename>' @help = "Imports cards from the specific csv file.\nNote that if the file does not contain an id column, all new cards will be created.\nOtherwise, existing cards with a matching id will be updated." end |
Instance Attribute Details
#help ⇒ Object (readonly)
Returns the value of attribute help.
6 7 8 |
# File 'lib/cardigan/command/import_cards.rb', line 6 def help @help end |
#usage ⇒ Object (readonly)
Returns the value of attribute usage.
6 7 8 |
# File 'lib/cardigan/command/import_cards.rb', line 6 def usage @usage end |
Instance Method Details
#execute(filename) ⇒ Object
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/cardigan/command/import_cards.rb', line 14 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 |csv| csv.to_a.each do |row| if header if id_index and row[id_index] id = row[id_index] card = @repository[id] if @repository.exist?(id) end if card puts "updating #{id}" else id ||= UUIDTools::UUID.random_create.to_s card = {} puts "creating new card with id #{id}" end editor = Cardigan::CardEditor.new(card, @io) header.each_with_index do |field, index| editor.set field, row[index] end @repository[id] = card else header = row id_index = header.find_index('id') end end end end |