Project

General

Profile

Download (1.88 KB) Statistics
| Branch: | Tag: | Revision:

hammer-cli-csv / lib / hammer_cli_csv / locations.rb @ c06f1783

1
module HammerCLICsv
2
  class CsvCommand
3
    class LocationsCommand < BaseCommand
4
      command_name 'locations'
5
      desc         'import or export locations'
6

    
7
      PARENT = 'Parent Location'
8

    
9
      def export(csv)
10
        csv << [NAME, PARENT]
11
        @api.resource(:locations).call(:index, {:per_page => 999999})['results'].each do |location|
12
          csv << [location['name'], '']
13
        end
14
      end
15

    
16
      def import
17
        @existing = {}
18
        @api.resource(:locations).call(:index, {:per_page => 999999})['results'].each do |location|
19
          @existing[location['name']] = location['id'] if location
20
        end
21

    
22
        thread_import do |line|
23
          create_locations_from_csv(line)
24
        end
25
      end
26

    
27
      def create_locations_from_csv(line)
28
        count(line[COUNT]).times do |number|
29
          name = namify(line[NAME], number)
30
          location_id = @existing[name]
31
          if !location_id
32
            print "Creating location '#{name}'... " if option_verbose?
33
            @api.resource(:locations).call(:create, {
34
                                             'location' => {
35
                                               'name' => name,
36
                                               'parent_id' => foreman_location(:name => line[PARENT])
37
                                             }
38
                                           })
39
          else
40
            print "Updating location '#{name}'... " if option_verbose?
41
            @api.resource(:locations).call(:update, {
42
                                             'id' => location_id,
43
                                             'location' => {
44
                                               'parent_id' => foreman_location(:name => line[PARENT])
45
                                             }
46
                                           })
47
          end
48
          print "done\n" if option_verbose?
49
        end
50
      end
51
    end
52
  end
53
end