Class: CSV

Inherits:
Object show all
Defined in:
lib/webget_ramp/csv.rb

Class Method Summary collapse

Class Method Details

.http_headers(options = {}) ⇒ Object

Return HTTP headers for a typical CSV file download without caching.

Options

- filename: defaults to "data.csv"
- request: the incoming http request, which is used to return MSIE-specific headers

Example

headers = CSV.http_headers("myfile.csv")

Example for Rails

response.headers.merge CSV.http_headers("myfile.csv")

Ideas from stackoverflow.com/questions/94502/in-rails-how-to-return-records-as-a-csv-file/94520



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/webget_ramp/csv.rb', line 18

def self.http_headers(options={})
filename = options[:filename] || 'data.csv'
options=self.http_headers_adjust_for_broken_msie(options)
content_type = options[:content_type] || 'text/csv'
return options[:cache] \
? {
   'Content-Type' => content_type,
   'Content-Disposition' => "attachment; filename=\"#{filename}\"",
  } \
: {
   'Content-Type' => content_type,
   'Cache-Control' => 'no-cache, must-revalidate, post-check=0, pre-check=0',
   'Expires' => "0",
   'Pragma' => 'no-cache',
   'Content-Disposition' => "attachment; filename=\"#{filename}\"",
  }
end

.http_headers_adjust_for_broken_msie(options = {}) ⇒ Object

Helper to try to “do the right thing” for the common case of Rails & MS IE.

Rails automatically defines a request object, that has an env HTTP_USER_AGENT.



41
42
43
44
45
46
47
48
49
# File 'lib/webget_ramp/csv.rb', line 41

def self.http_headers_adjust_for_broken_msie(options={})
  request = options[:request] || request 
  msie = (request and request.env['HTTP_USER_AGENT'] =~ /msie/i)
  if msie
    options[:content_type]||='text/plain''})'
    options[:cache]||=false
  end
  options
end