Class: AssessmentConverter

Inherits:
Converter show all
Defined in:
backend/app/converters/assessment_converter.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Converter

for, #get_output_path, #import_options, import_options, inherited, #initialize, list_import_types, register_converter, #remove_files

Constructor Details

This class inherits a constructor from Converter

Class Method Details

.boolean_to_sObject



254
255
256
257
# File 'backend/app/converters/assessment_converter.rb', line 254

def self.boolean_to_s
  @boolean_to_s ||= Proc.new {|val| val.to_s.upcase.match(/\A(1|T|Y|YES|TRUE)\Z/) ? 'true' : 'false' }
  @boolean_to_s
end

.configurationObject

overriding this because we are special this importer is self configuring, so it has to configure itself on each run



19
20
21
# File 'backend/app/converters/assessment_converter.rb', line 19

def self.configuration
  @config ||= self.configure
end

.configureObject



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
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'backend/app/converters/assessment_converter.rb', line 67

def self.configure
  config = {}
  records = 0
  agents = 0
  reviewers = 0

  @field_headers.each do |section_field|
    (section, field) = section_field.split('_', 2)
    name = section_field
    data_path = "assessment.#{field}"
    val_filter = nil
    val_filter ||= @booleans.include?(section_field) ? normalize_boolean : nil
    val_filter ||= @dates.include?(section_field) ? reformat_date : nil

    if section_field.start_with?('basic_record')
      records += 1
      data_path = "records_#{records}.uri"
      val_filter = record_to_uri

      config["records_#{records}".intern] = {
        :record_type => Proc.new {|data|
          JSONModel.parse_reference(data['uri'])[:type]
        },
        :on_row_complete => Proc.new { |cache, record|

          assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }

          assessment.records << {'ref' => record.uri}

          # nil the record in the cache to avoid having it created
          cache.map! {|obj| (obj && obj.key == record.key) ? nil : obj}
        }
      }


    elsif section_field.start_with?('basic_surveyed_by')
      agents += 1
      data_path = "agents_#{agents}.uri"
      val_filter = user_to_uri

      config["agents_#{agents}".intern] = {
        :record_type => Proc.new {|data|
          JSONModel.parse_reference(data['uri'])[:type]
        },
        :on_row_complete => Proc.new { |cache, agent|

          assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }

          assessment.surveyed_by << {'ref' => agent.uri}

          # nil the agent in the cache to avoid having it created
          cache.map! {|obj| (obj && obj.key == agent.key) ? nil : obj}
        }
      }

    elsif section_field.start_with?('basic_reviewer')
      reviewers += 1
      data_path = "reviewers_#{reviewers}.uri"
      val_filter = user_to_uri

      config["reviewers_#{reviewers}".intern] = {
        :record_type => Proc.new {|data|
          JSONModel.parse_reference(data['uri'])[:type]
        },
        :on_row_complete => Proc.new { |cache, agent|

          assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }

          assessment.reviewer << {'ref' => agent.uri}

          # nil the agent in the cache to avoid having it created
          cache.map! {|obj| (obj && obj.key == agent.key) ? nil : obj}
        }
      }

    elsif section == 'format'
      defn = match_definition('format', field)

      data_path = "#{section_field}.value"
      val_filter = boolean_to_s

      config[section_field.intern] = {
        :record_type => 'assessment_attribute',
        :on_row_complete => Proc.new { |cache, attr|
          if attr.value == 'true'
            assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }
            assessment.formats << { :value => 'true', :definition_id => defn[:id] }
          end
        }
      }

    elsif section == 'rating'

      if field.end_with?('_note')
        data_path = section_field.sub(/_note$/, '') + '.note'
      else
        defn = match_definition('rating', field)

        data_path = "#{section_field}.value"

        config[section_field.intern] = {
          :record_type => 'assessment_attribute',
          :on_row_complete => Proc.new { |cache, attr|
            assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }
            assessment.formats << {
              :value => attr.value,
              :note => attr.note,
              :definition_id => defn[:id]
            }
          }
        }

      end

    elsif section == 'conservation'
      defn = match_definition('conservation_issue', field)

      data_path = "#{section_field}.value"
      val_filter = boolean_to_s

      config[section_field.intern] = {
        :record_type => 'assessment_attribute',
        :on_row_complete => Proc.new { |cache, attr|
          if attr.value == 'true'
            assessment = cache.find {|obj| obj && obj.class.record_type == 'assessment' }
            assessment.conservation_issues << { :value => 'true', :definition_id => defn[:id] }
          end
        }
      }
    end

    config[name] = [val_filter, data_path]
  end

  config
end

.configure_cell_handlers(row) ⇒ Object



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
# File 'backend/app/converters/assessment_converter.rb', line 34

def self.configure_cell_handlers(row)
  if row[0] == 'basic'
    # this is the section header row
    @section_headers = row
    @field_headers = []
    @cell_handlers = []
    @defns = nil
    # return empty cell handlers so that #run calls us again
    return [[], []]
  end

  records = 0
  agents = 0
  reviewers = 0
  @field_headers = @section_headers.zip(row).map {|section, field|
    hdr = "#{section}_#{field}"
    if hdr == 'basic_record'
      records += 1
      hdr += "_#{records}"
    elsif hdr == 'basic_surveyed_by'
      agents += 1
      hdr += "_#{agents}"
    elsif hdr == 'basic_reviewer'
      reviewers += 1
      hdr += "_#{reviewers}"
    end
    # our parent is very strict about headers ...
    normalize_label(hdr)
  }

  super(@field_headers)
end

.import_types(show_hidden = false) ⇒ Object



204
205
206
207
208
209
210
211
# File 'backend/app/converters/assessment_converter.rb', line 204

def self.import_types(show_hidden = false)
  [
   {
     :name => "assessment_csv",
     :description => "Import Assessment records from a CSV file"
   }
  ]
end

.instance_for(type, input_file) ⇒ Object



213
214
215
216
217
218
219
# File 'backend/app/converters/assessment_converter.rb', line 213

def self.instance_for(type, input_file)
  if type == "assessment_csv"
    self.new(input_file)
  else
    nil
  end
end

.match_definition(type, field) ⇒ Object



293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
# File 'backend/app/converters/assessment_converter.rb', line 293

def self.match_definition(type, field)
  @defns ||= AssessmentAttributeDefinitions.get(Thread.current[:request_context][:repo_id]).definitions
  type_defns = @defns.select {|d| d[:type] == type}
  matched_defns = type_defns.select {|d| normalize_label(d[:label]) == normalize_label(field)}

  if matched_defns.empty?
    raise "Unknown #{type} in column header: #{field}. " +
      "Allowed #{type}s for this repository: #{type_defns.map {|d| d[:label]}.join(', ')}"
  end

  if matched_defns.length > 1
    raise "Ambiguous #{type} type in column header: #{field}. " +
      "Matched #{matched_defns.map {|d| d[:label]}.join(', ')}"
  end

  matched_defns.first
end

.normalize_booleanObject



248
249
250
251
# File 'backend/app/converters/assessment_converter.rb', line 248

def self.normalize_boolean
  @normalize_boolean ||= Proc.new {|val| val.to_s.upcase.match(/\A(1|T|Y|YES|TRUE)\Z/) ? true : false }
  @normalize_boolean
end

.normalize_label(label) ⇒ Object



225
226
227
# File 'backend/app/converters/assessment_converter.rb', line 225

def self.normalize_label(label)
  label.strip.downcase.gsub(/[^a-z0-9]+/, '_').gsub(/_+$/, '')
end

.reconfigure!Object



23
24
25
# File 'backend/app/converters/assessment_converter.rb', line 23

def self.reconfigure!
  @config = nil
end

.record_to_uriObject



260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
# File 'backend/app/converters/assessment_converter.rb', line 260

def self.record_to_uri
  @record_types ||=  %w{resource archival_object accession digital_object}
  @record_to_uri ||= Proc.new {|val|
    (junk, type, id) = val.downcase.match(/^\s*([a-z_]*?)[_\/\. ]+(\d+)\s*$/).to_a

    unless type && id
      raise "Invalid basic_record reference #{val}. " +
        "Must have the form [#{@record_types.join('|')}][delimiter]id. " +
        "Where [delimiter] can be any of _ / . or space."
    end

    unless @record_types.include?(type)
      raise "Invalid basic_record reference #{val}. " +
        "Record type #{type} not allowed. Must be one of #{@record_types.join(', ')}."
    end

    JSONModel::JSONModel(type.intern).uri_for(id, :repo_id => Thread.current[:request_context][:repo_id])
  }
  @record_to_uri
end

.reformat_dateObject



230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'backend/app/converters/assessment_converter.rb', line 230

def self.reformat_date
  # excel annoyingly reformats dates in csv, so let's try to do the right thing
  @reformat_date ||= Proc.new {|val|
    if val.index('/')
      # assume it's mm/dd/yy unless mm is > 12
      (m, d, y) = val.split('/')
      # assume it's this century unless yy is greater than this year
      y = y.length == 2 ? (y.to_i > Date.today.year.to_s[2..3].to_i ? "19#{y}" : "20#{y}") : y
      (m.to_i > 12 ? Date.new(y.to_i, d.to_i, m.to_i) : Date.new(y.to_i, m.to_i, d.to_i)).iso8601
    else
      # this probably isn't required, but it's nice to be reassured
      Date.parse(val).iso8601
    end
  }
  @reformat_date
end

.user_to_uriObject



282
283
284
285
286
287
288
289
290
291
# File 'backend/app/converters/assessment_converter.rb', line 282

def self.user_to_uri
  @user_to_uri ||= Proc.new {|val|
    unless (user = User.find(:username => val))
      raise "User '#{val}' does not exist"
    end

    User.to_jsonmodel(user).agent_record['ref']
  }
  @user_to_uri
end

Instance Method Details

#runObject



27
28
29
30
31
# File 'backend/app/converters/assessment_converter.rb', line 27

def run
  self.class.reconfigure!

  super
end