-
Notifications
You must be signed in to change notification settings - Fork 121
/
presenter_factory.rb
60 lines (53 loc) · 2.06 KB
/
presenter_factory.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
module Hyrax
# Responsible building an Array of presenters based on IDs and presenter class given
# @note The given IDs are loaded from SOLR
class PresenterFactory
class << self
# @param [Array] args any other arguments to pass to the presenters
# @param [Array] ids the list of ids to load
# @param [Class] presenter_class the class of presenter to make
# @return [Array] presenters for the documents in order of the ids (as given)
def build_for(ids:, presenter_class:, args: [])
new(ids, presenter_class, *args)
end
# @param [Array] ids the list of ids to load
# @param [Class] klass the class of presenter to make
# @param [Array] args any other arguments to pass to the presenters
# @return [Array] presenters for the documents in order of the ids
def build_presenters(ids, klass, *args)
build_for(ids: ids, presenter_class: klass, args: args)
end
deprecation_deprecate build_presenters: "use .build_for instead"
end
attr_reader :ids, :presenter_class, :args
alias klass presenter_class
deprecation_deprecate klass: "use presenter_class instead"
def initialize(ids, presenter_class, *args)
@ids = ids
@presenter_class = presenter_class
@args = args
end
def build
return [] if ids.blank?
docs = load_docs
ids.map do |id|
solr_doc = docs.find { |doc| doc.id == id }
presenter_class.new(solr_doc, *args) if solr_doc
end.compact
end
private
# @return [Array<SolrDocument>] a list of solr documents in no particular order
def load_docs
query("{!terms f=id}#{ids.join(',')}", rows: 1000)
.map { |res| ::SolrDocument.new(res) }
end
# Query solr using POST so that the query doesn't get too large for a URI
def query(query, args = {})
args[:q] = query
args[:qt] = 'standard'
conn = ActiveFedora::SolrService.instance.conn
result = conn.post('select', data: args)
result.fetch('response').fetch('docs')
end
end
end