Class: Xport::Export

Inherits:
Object
  • Object
show all
Defined in:
lib/xport/export.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(objects = []) ⇒ Export

Returns a new instance of Export.



13
14
15
16
# File 'lib/xport/export.rb', line 13

def initialize(objects = [])
  @objects = objects
  @builder = Xport::ExportBuilder.new(self, &builder_block)
end

Instance Attribute Details

#builderObject (readonly)

Returns the value of attribute builder.



5
6
7
# File 'lib/xport/export.rb', line 5

def builder
  @builder
end

#objectsObject (readonly)

Returns the value of attribute objects.



5
6
7
# File 'lib/xport/export.rb', line 5

def objects
  @objects
end

#workbookObject (readonly)

Returns the value of attribute workbook.



5
6
7
# File 'lib/xport/export.rb', line 5

def workbook
  @workbook
end

Class Method Details

.columns(&block) ⇒ Object



9
10
11
# File 'lib/xport/export.rb', line 9

def self.columns(&block)
  self.builder_block = block
end

Instance Method Details

#download(filename:, user: nil) ⇒ Object

TODO: Extract to xport-downloads?



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/xport/export.rb', line 31

def download(filename:, user: nil)
  return unless objects.respond_to?(:to_sql)
  download                   = download_class.new
  download.user              = user
  download.export_klass_name = self.class.name

  if objects.respond_to?(:model)
    download.export_model_name = objects.model.name
  end
  if respond_to?(:additional_columns)
    download.export_additional_columns = additional_columns
  end
  # TODO: Remove `unprepared_statement` call when `to_sql` is fixed
  # https://github.com/rails/rails/issues/18379
  object_class.connection.unprepared_statement do
    download.query = objects.to_sql
  end
  download.filename = filename
  download.save!
  download.schedule_export!
  download
end

#download_classObject



54
55
56
57
58
59
60
61
# File 'lib/xport/export.rb', line 54

def download_class
  module_name = self.class.to_s.deconstantize
  if module_name.present?
    "#{module_name}::Download".constantize
  else
    Download
  end
end

#object_classObject



26
27
28
# File 'lib/xport/export.rb', line 26

def object_class
  self.class.name.sub(/Export/, '').singularize.constantize
end

#to_file(formatter = nil, &block) ⇒ Object



18
19
20
21
22
23
24
# File 'lib/xport/export.rb', line 18

def to_file(formatter = nil, &block)
  preload!
  # TODO: There shouldn't be a default formatter
  formatter ||= Xport::Axlsx::Formatter.new(self)
  write_contents(formatter, &block)
  formatter.to_file
end