Class: Workarea::ExportReport

Inherits:
Object
  • Object
show all
Defined in:
app/services/workarea/export_report.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(report, csv) ⇒ ExportReport

Returns a new instance of ExportReport.



5
6
7
8
# File 'app/services/workarea/export_report.rb', line 5

def initialize(report, csv)
  @report = report
  @csv = csv
end

Instance Attribute Details

#csvObject (readonly)

Returns the value of attribute csv.



3
4
5
# File 'app/services/workarea/export_report.rb', line 3

def csv
  @csv
end

#reportObject (readonly)

Returns the value of attribute report.



3
4
5
# File 'app/services/workarea/export_report.rb', line 3

def report
  @report
end

Instance Method Details

#collectionObject



45
46
47
48
49
50
# File 'app/services/workarea/export_report.rb', line 45

def collection
  @collection ||= Mongo::Collection.new(
    report.reporting_class.collection.database,
    "#{report.class.name.demodulize.underscore}_#{Time.current.to_s(:export)}"
  )
end

#destroy!Object



37
38
39
# File 'app/services/workarea/export_report.rb', line 37

def destroy!
  collection.drop
end

#ignored_fieldsObject



52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/services/workarea/export_report.rb', line 52

def ignored_fields
  @ignored_fields ||= begin
    results = []

    for_each do |result|
      result.to_h.each do |key, value|
        results << key if value.is_a?(ApplicationDocument)
      end
    end

    results
  end
end

#perform!Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'app/services/workarea/export_report.rb', line 18

def perform!
  save!
  has_headers = false

  for_each do |result|
    hash = result.to_h.except(*ignored_fields)

    unless has_headers
      csv << hash.keys
      has_headers = true
    end

    csv << hash.values
  end

ensure
  destroy!
end

#save!Object



10
11
12
13
14
15
16
# File 'app/services/workarea/export_report.rb', line 10

def save!
  report
    .reporting_class
    .collection
    .aggregate(report.aggregation + [{ '$out' => collection.name }])
    .first # make the aggregation run
end

#view_modelObject



41
42
43
# File 'app/services/workarea/export_report.rb', line 41

def view_model
  @view_model ||= "Workarea::Admin::Reports::#{report.class.to_s.demodulize}ViewModel".constantize
end