lib/decisive/template_handler.rb in decisive-0.6.3 vs lib/decisive/template_handler.rb in decisive-0.7.0
- old
+ new
@@ -62,13 +62,77 @@
else
RenderContext.new(records, filename, block)
end
end
- def xls worksheets, filename:, &block
- XLSContext.new(worksheets, filename, block)
+ def xls worksheets=nil, filename:, &block
+ if worksheets
+ XLSContext.new(worksheets, filename, block)
+ else
+ XLSWithWorksheetsContext.new(filename, [], &block)
+ end
end
end
+
+ class XLSWithWorksheetsContext < Struct.new(:filename, :worksheets)
+ class Worksheet < Struct.new(:records, :name, :block); end
+
+ def initialize *args, &block
+ super
+ instance_eval &block
+ end
+
+ def to_xls
+ to_string(render(Spreadsheet::Workbook.new))
+ end
+
+ def csv?
+ false
+ end
+
+ private
+
+ def worksheet records, name:, &block
+ worksheets.push Worksheet.new(records, name, block)
+ end
+
+ def render xls
+ worksheets.each do |worksheet|
+ sheet = xls.create_worksheet(name: sanitize_name(worksheet.name))
+
+ rows = to_array(worksheet)
+
+ rows.each.with_index do |row, index|
+ sheet.row(index).concat row
+ end
+ end
+ xls
+ end
+
+ def sanitize_name name
+ name
+ .gsub(/[\[\]\*\?:\/\\\t\n\r]/, " ")
+ .gsub(/^'/, "")
+ .gsub(/'$/, "")
+ .strip
+ .slice(0,31)
+ end
+
+ def to_array worksheet
+ context = RenderContext.new(worksheet.records, nil, worksheet.block)
+ context.send(:header) + context.send(:body)
+ end
+
+ def to_string xls
+ io = StringIO.new
+ xls.write(io)
+ io.rewind
+ string = io.read
+ string.force_encoding(Encoding::ASCII_8BIT)
+ string
+ end
+ end
+
class XLSContext < Struct.new(:worksheets, :filename, :block)
def to_xls
to_string(render(Spreadsheet::Workbook.new))
end