-
Notifications
You must be signed in to change notification settings - Fork 2
/
import_service.rb
90 lines (80 loc) · 2.59 KB
/
import_service.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
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
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
module Tufts
##
# A service for creating a persistent resource based on a
# `Hyrax::UploadedFile` and an associated `XmlImport`.
#
# @example
# ImportService.import_object!(import: my_import,
# file: import_file,
# object_id: 'a_fedora_id')
class ImportService
##
# @!attribute file [rw]
# @return [Hyrax::UploadedFile]
# @!attribute files [rw]
# @return [Array<Hyrax::UploadedFile>]
# @!attribute import [rw]
# @return [XmlImport]
# @!attribute object_id [rw]
# @return [String]
attr_accessor :file, :files, :import, :object_id
##
# @param file [Hyrax::UploadedFile]
# @param import [XmlImport]
#
# @return [ActiveFedora::Core]
# @see #import_object!
def self.import_object!(import:, file: nil, object_id: nil, files: [])
new(import: import, file: file, object_id: object_id, files: files).import_object!
end
##
# @param file [Hyrax::UploadedFile]
# @param import [XmlImport]
def initialize(import:, file: nil, files: [], object_id: nil)
if file
warn 'Initializing ImportService with a single file is deprecated, ' \
'use the `files` param instead'
end
@file = file || files.first
@import = import
@object_id = object_id
@files = files
end
##
# Imports the object.
#
# @return [ActiveFedora::Core]
def import_object!
object = record.build_object(id: object_id)
creator = User.find(file.user_id)
ability = ::Ability.new(creator)
env = Hyrax::Actors::Environment.new(object, ability, attributes)
Hyrax::CurationConcern.actor.create(env) ||
raise(ImportError, "Failed to create object #{object.id}\n The actor stack returned `false`.")
object
end
##
# @return [ImportRecord]
def record
# UploadedFile -> Uploader -> CarrierWave::SanitizedFile -> String
import.record_for(file: file.file.file.filename)
end
class ImportError < RuntimeError; end
private
##
# @private
# @return [HashWithIndifferentAccess]
def attributes
{ uploaded_files: file_ids,
member_of_collection_ids: record.collections,
thumbnail: record.thumbnail,
transcript: record.transcript,
representative: record.representative }.with_indifferent_access
end
##
# @private
def file_ids
files.empty? ? [file.id] : files.map(&:id)
end
end
end