Class: ActionView::TemplateHandlers::CsvBuilder
- Inherits:
-
TemplateHandler
- Object
- TemplateHandler
- ActionView::TemplateHandlers::CsvBuilder
- Includes:
- Compilable
- Defined in:
- lib/csv_builder.rb
Overview
Template handler for csv templates
Add rows to your CSV file in the template by pushing arrays of columns into csv
# First row
csv << [ 'cell 1', 'cell 2' ]
# Second row
csv << [ 'another cell value', 'and another' ]
# etc...
You can set the default filename for that a browser will use for ‘save as’ by setting @filename instance variable in your controller’s action method e.g.
@filename = 'report.csv'
You can also set the input encoding and output encoding by setting @input_encoding and @output_encoding instance variables. These default to ‘UTF-8’ and ‘LATIN1’ respectively. e.g.
@output_encoding = 'UTF-8'
Class Method Summary collapse
Instance Method Summary collapse
Class Method Details
.line_offset ⇒ Object
32 33 34 |
# File 'lib/csv_builder.rb', line 32 def self.line_offset 9 end |
Instance Method Details
#compile(template) ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
# File 'lib/csv_builder.rb', line 36 def compile(template) " begin\n\n unless defined?(ActionMailer) && defined?(ActionMailer::Base) && controller.is_a?(ActionMailer::Base)\n @filename ||= \"\\\#{controller.action_name}.csv\"\n controller.response.headers[\"Content-Type\"] ||= 'text/csv'\n controller.response.headers['Content-Disposition'] = \"attachment; filename=\\\#{@filename}\"\n end\n\n result = FasterCSV.generate do |csv|\n \#{template.source}\n end\n\n # Transliterate into the required encoding if necessary\n # TODO: make defaults configurable\n @input_encoding ||= 'UTF-8'\n @output_encoding ||= 'LATIN1'\n\n if @input_encoding == @output_encoding\n result\n else\n # TODO: do some checking to make sure iconv works correctly in\n # current environment. See ActiveSupport::Inflector#transliterate\n # definition for details\n #\n # Not using the more standard //IGNORE//TRANLIST because it raises\n # Iconv::IllegalSequence for some inputs\n c = Iconv.new(\"\\\#{@output_encoding}//TRANSLIT//IGNORE\", @input_encoding)\n c.iconv(result)\n end\n\n rescue Exception => e\n RAILS_DEFAULT_LOGGER.warn(\"Exception \\\#{e} \\\#{e.message} with class \\\#{e.class.name} thrown when rendering CSV\")\n raise e\n end\n EOV\nend\n" |