Class: SpotlightSearch::ExportJob

Inherits:
ApplicationJob
  • Object
show all
Defined in:
app/jobs/spotlight_search/export_job.rb

Instance Method Summary collapse

Instance Method Details

#create_excel(records, klass) ⇒ Object

Creating excel with the passed records Keys as headers and values as row



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'app/jobs/spotlight_search/export_job.rb', line 31

def create_excel(records, klass)
  records = records.as_json
  headers = records.first.keys
  size_arr = []
  headers.size.times { size_arr << 22 }
  xl = Axlsx::Package.new
  xl.workbook.add_worksheet do |sheet|
    sheet.add_row headers, b: true
    records.each do |record|
      sheet.add_row record.values
    end
    sheet.column_widths *size_arr
  end
  file_location = "#{Rails.root}/public/export_#{klass}_#{Time.now.to_s}"
  xl.serialize(file_location)
  file_location
end

#get_records(klass, filters, columns) ⇒ Object



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'app/jobs/spotlight_search/export_job.rb', line 11

def get_records(klass, filters, columns)
  records = klass
  if filters['filters'].present?
    filters['filters'].each do |scope, scope_args|
      if scope_args.is_a?(Array)
        records = records.send(scope, *scope_args)
      else
        records = records.send(scope, scope_args)
      end
    end
  end
  if filters['sort'].present?
    records = records.order("#{filters['sort']['sort_column']} #{filters['sort']['sort_direction']}")
  end
  columns = columns.map(&:to_sym)
  records.select(*columns)
end

#perform(email, klass, columns = nil, filters = nil) ⇒ Object



3
4
5
6
7
8
9
# File 'app/jobs/spotlight_search/export_job.rb', line 3

def perform(email, klass, columns = nil, filters = nil)
  records = get_records(klass, filters, columns)
  file_path = create_excel(records, klass.name)
  subject = "#{klass.name} export at #{Time.now}"
  ExportMailer.send_excel_file(email, file_path, subject).deliver_now
  File.delete(file_path)
end