Class: Tofulcrum::CLI

Inherits:
Thor
  • Object
show all
Defined in:
lib/tofulcrum.rb

Instance Method Summary collapse

Instance Method Details

#import(file, form_id, api_key, mapping = nil) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'lib/tofulcrum.rb', line 25

def import(file, form_id, api_key, mapping=nil)

  Fulcrum::Api.configure do |config|
    config.uri = API_URL
    config.key = api_key
  end

  row_index = 0
  upload_index = 0

  column_mapping = []
  records = []
  system_columns = {}

  CSV.foreach(file) do |row|
    is_header = row_index == 0

    if is_header
      system_columns = find_system_columns(row)
      raise 'Unable to find latitude/longitude columns' unless system_columns[:latitude] && system_columns[:longitude]

      user_cols = user_columns(row, system_columns)

      column_mapping = find_mapping_columns(form_id, user_cols, row, mapping)
    else
      form_values = {}

      column_mapping.each do |map|
        value = nil

        case map[:field]['type']
        when 'ChoiceField'
          value = { choice_values: row[map[:index]].split(',').map(&:strip) } rescue nil
        when 'PhotoField'
          value = []
          row[map[:index]].split(',').map(&:strip).each do |photo|
            if File.exist?(photo)
              key = SecureRandom.uuid
              file = File.open(photo)
              Fulcrum::Photo.create(file, "image/jpeg", key, "")
              value << { "photo_id" => key }
            end
          end
        else
          value = row[map[:index]]
        end

        form_values[map[:field]['key']] = value if value
      end

      record = {
        record: {
          form_id: form_id,
          form_values: form_values
        }
      }

      system_columns.each do |attr, index|
        record[:record][attr] = row[index]
      end

      records << record
    end

    row_index += 1
  end

  thread_count = 8

  mutex = Mutex.new

  thread_count.times.map {
    Thread.new(records) do |recs|
      while record = mutex.synchronize { recs.pop }
        Fulcrum::Record.create(record)
        mutex.synchronize {
          print "#{upload_index.to_s.rjust(10, ' ')} records uploaded\r"
          upload_index += 1
        }
      end
    end
  }.each(&:join)
end

#xls(file) ⇒ Object



20
21
22
# File 'lib/tofulcrum.rb', line 20

def xls(file)
  Fulcrum::XlsReader.read(file)
end