ruby-on-railscsvcharacter-encodingcjkshift-jis

Set character encoding when generating CSV file Rails 4.2


I have a module to generate csv file of the model when included.

# app/models/concerns/csv_exportable.rb
module CsvExportable
  extend ActiveSupport::Concern

  included do
    def self.to_csv(options = {})
      CSV.generate(options) do |csv|
        csv << column_names
        all.each do |thismodel|
          csv << thismodel.attributes.values_at(*column_names)
        end
      end
    end
  end
end

and I include the module in models for which I want to generate csv file

# app/models/product.rb
class Reason < ActiveRecord::Base
  include CsvExportable
  .
  .
end

In my controller I do

respond_to do |format|
  format.html
  format.csv { send_data @products.to_csv, filename: 'products.csv' }
end

I want to set the character encoding of generated csv file to Shift_JIS instead of default utf-8. What is the best way to do this ? Thank you

EDIT:

I tried

format.csv { send_data (@products.to_csv).encode("SHIFT-JIS"), filename: 'products.csv' }

now I am getting an error Encoding::ConverterNotFoundError code converter not found (UTF-8 to SHIFT-JIS)


Solution

  • format.csv { 
      send_data (@products.to_csv).encode(Encoding::SJIS), 
      filename: 'products.csv', 
      type: 'text/csv; charset=shift_jis'
    }
    

    Did the trick