Class: CsvBuilder::StreamingTemplateHandler

Inherits:
ActionView::Template::Handler
  • Object
show all
Includes:
ActionView::Template::Handlers::Compilable
Defined in:
lib/csv_builder/template_handler.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'

Instance Method Summary collapse

Instance Method Details

#compile(template) ⇒ Object



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/csv_builder/template_handler.rb', line 84

def compile(template)
  
  <<-EOV
  begin
       
    unless defined?(ActionMailer) && defined?(ActionMailer::Base) && controller.is_a?(ActionMailer::Base)
      @filename ||= "\#{controller.action_name}.csv"
      if controller.request.env['HTTP_USER_AGENT'] =~ /msie/i
        response.headers['Pragma'] = 'public'
        response.headers["Content-type"] = "text/plain"
        response.headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
        response.headers['Content-Disposition'] = "attachment; filename=\#{@filename}"
        response.headers['Expires'] = "0"
      else
        response.headers["Content-Type"] ||= 'text/csv'
        response.headers["Content-Disposition"] = "attachment; filename=\#{@filename}"
        response.headers["Content-Transfer-Encoding"] = "binary"
      end
    end
    
    if @streaming
      template = Proc.new {|csv|
        #{template.source}
      }
      CsvBuilder::Streamer.new(template)
    else 
      output = CsvBuilder::CSV_LIB.generate(@csv_options || {}) do |faster_csv|
        csv = CsvBuilder::TransliteratingFilter.new(faster_csv, @input_encoding || 'UTF-8', @output_encoding || 'LATIN1')
        #{template.source}
      end
      output
    end
  rescue Exception => e
    Rails.logger.warn("Exception \#{e} \#{e.message} with class \#{e.class.name} thrown when rendering CSV")
    raise e
  end
  EOV
end