Class: XlsExporter::Exporter
- Inherits:
-
Object
- Object
- XlsExporter::Exporter
- Defined in:
- lib/xls_exporter/exporter.rb
Class Method Summary collapse
Instance Method Summary collapse
- #add_sheet(sheet_name = nil) ⇒ Object
- #body(new_body) ⇒ Object
- #export_models(scope, *columns) ⇒ Object
- #filename(new_filename) ⇒ Object
- #headers(*args) ⇒ Object
- #humanize_columns(columns) ⇒ Object
-
#initialize ⇒ Exporter
constructor
A new instance of Exporter.
- #save! ⇒ Object
- #save_sheet! ⇒ Object
Constructor Details
#initialize ⇒ Exporter
Returns a new instance of Exporter.
11 12 13 |
# File 'lib/xls_exporter/exporter.rb', line 11 def initialize @book = Spreadsheet::Workbook.new end |
Class Method Details
.export(&block) ⇒ Object
5 6 7 8 9 |
# File 'lib/xls_exporter/exporter.rb', line 5 def self.export(&block) exporter = new exporter.instance_exec(&block) exporter.save! end |
Instance Method Details
#add_sheet(sheet_name = nil) ⇒ Object
15 16 17 18 19 20 21 22 |
# File 'lib/xls_exporter/exporter.rb', line 15 def add_sheet(sheet_name = nil) save_sheet! if @sheet @headers = [] @body = [] @sheet = @book.create_worksheet @sheet.name = sheet_name end |
#body(new_body) ⇒ Object
32 33 34 |
# File 'lib/xls_exporter/exporter.rb', line 32 def body(new_body) @body = new_body end |
#export_models(scope, *columns) ⇒ Object
43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/xls_exporter/exporter.rb', line 43 def export_models(scope, *columns) headers(*humanize_columns(columns)) to_body = scope.map do |instance| columns.map do |column| column = column.values.first if column.is_a? Hash if column.is_a? Proc instance.instance_exec(&column) elsif column.is_a? Symbol instance.send column end end end body to_body end |
#filename(new_filename) ⇒ Object
24 25 26 |
# File 'lib/xls_exporter/exporter.rb', line 24 def filename(new_filename) @filename = new_filename end |
#headers(*args) ⇒ Object
28 29 30 |
# File 'lib/xls_exporter/exporter.rb', line 28 def headers(*args) @headers = args end |
#humanize_columns(columns) ⇒ Object
36 37 38 39 40 41 |
# File 'lib/xls_exporter/exporter.rb', line 36 def humanize_columns(columns) columns.map do |column| column = column.keys.first if column.is_a? Hash column.to_s.humanize end end |
#save! ⇒ Object
65 66 67 68 69 70 71 72 73 74 |
# File 'lib/xls_exporter/exporter.rb', line 65 def save! save_sheet! if @filename.present? filename = "./#{@filename}_#{Time.now.to_i}.xls" @book.write(filename) puts "Report has been saved as #{filename}" else @book end end |
#save_sheet! ⇒ Object
58 59 60 61 62 63 |
# File 'lib/xls_exporter/exporter.rb', line 58 def save_sheet! @sheet.row(0).concat(@headers) @body.each_with_index do |row, index| @sheet.row(index + 1).concat(row) end end |