Class: FactoryDumps::Exporter
- Inherits:
-
Object
- Object
- FactoryDumps::Exporter
- Defined in:
- lib/factory_dumps/exporter.rb
Instance Method Summary collapse
-
#initialize(factory_name) ⇒ Exporter
constructor
A new instance of Exporter.
- #to_csv(count = 1, attributes = nil) ⇒ Object
- #to_excel(count = 1, attributes = nil, filename = "export.xls") ⇒ Object
Constructor Details
#initialize(factory_name) ⇒ Exporter
Returns a new instance of Exporter.
7 8 9 10 11 |
# File 'lib/factory_dumps/exporter.rb', line 7 def initialize(factory_name) @factory_name = factory_name @factory = FactoryBot.factories.find(@factory_name) raise KeyError, "Factory '#{factory_name}' not found" unless @factory end |
Instance Method Details
#to_csv(count = 1, attributes = nil) ⇒ Object
13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/factory_dumps/exporter.rb', line 13 def to_csv(count = 1, attributes = nil) records = generate_records(count) attributes ||= get_default_attributes CSV.generate do |csv| csv << attributes records.each do |record| csv << attributes.map { |attr| record.send(attr) } end end end |
#to_excel(count = 1, attributes = nil, filename = "export.xls") ⇒ Object
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
# File 'lib/factory_dumps/exporter.rb', line 25 def to_excel(count = 1, attributes = nil, filename = "export.xls") records = generate_records(count) attributes ||= get_default_attributes workbook = WriteExcel.new(filename) worksheet = workbook.add_worksheet # Write headers attributes.each_with_index do |attr, col| worksheet.write(0, col, attr.to_s) end # Write data records.each_with_index do |record, row| attributes.each_with_index do |attr, col| worksheet.write(row + 1, col, record.send(attr)) end end workbook.close filename end |