Permalink
Browse files

Convert CSV files to Latin1 by default

This enables them to be read by Microsoft Excel
  • Loading branch information...
1 parent 948ebf0 commit 78f8785bf9e3ea442fe1766d0c3844187a27117f @mocoso mocoso committed Feb 10, 2009
Showing with 34 additions and 9 deletions.
  1. +7 −1 README
  2. +27 −8 lib/csv_builder.rb
View
8 README
@@ -33,7 +33,13 @@ setting <tt>@filename</tt> 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
+<tt>@input_encoding</tt> and <tt>@output_encoding</tt> instance variables.
+These default to 'utf-8' and 'latin1' respectively. e.g.
+
+ @output_encoding = 'utf-8'
+
You can also attach a csv file to mail sent out by your application by
including a snippet like the following in your mailer method
View
@@ -1,4 +1,5 @@
require 'fastercsv'
+require 'iconv'
module ActionView # :nodoc:
module TemplateHandlers
@@ -17,31 +18,49 @@ module TemplateHandlers
# e.g.
#
# @filename = 'report.csv'
-
+ #
+ # You can also set the input encoding and output encoding by setting
+ # <tt>@input_encoding</tt> and <tt>@output_encoding</tt> instance variables.
+ # These default to 'utf-8' and 'latin1' respectively. e.g.
+ #
+ # @output_encoding = 'utf-8'
+
class CsvBuilder < TemplateHandler
+
include Compilable
def self.line_offset
7
end
-
def compile(template)
<<-EOV
- unless defined?(ActionMailer) && defined?(ActionMailer::Base) && controller.is_a?(ActionMailer::Base)
- @filename ||= "\#{controller.action_name}.csv"
+ unless defined?(ActionMailer) && defined?(ActionMailer::Base) && controller.is_a?(ActionMailer::Base)
+ @filename ||= "\#{controller.action_name}.csv"
controller.response.headers["Content-Type"] ||= 'text/csv'
- controller.response.headers['Content-Disposition'] = "attachment; filename=\#{@filename}"
+ controller.response.headers['Content-Disposition'] = "attachment; filename=\#{@filename}"
end
-
+
result = FasterCSV.generate do |csv|
#{template.source}
end
- result
+ # Transliterate into the required encoding if necessary
+ # TODO: make defaults configurable
+ @input_encoding ||= 'utf-8'
+ @output_encoding ||= 'latin1'
+
+ if @input_encoding == @output_encoding
+ result
+ else
+ # TODO: do some checking to make sure iconv works correctly in current environment
+ # See ActiveSupport::Inflector#transliterate definition for details
+ Iconv.iconv("\#{@output_encoding}//ignore//translit", @input_encoding, result).to_s
+ end
+
EOV
end
end
end
-end
+end

0 comments on commit 78f8785

Please sign in to comment.