Created
January 19, 2017 11:49
-
-
Save sangkyoonnam/69bb67ed43f813771c35b89ad59522e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'active_support' | |
require 'csv' | |
module ExportToCsv | |
extend ActiveSupport::Concern | |
def to_csv(attributes = attribute_names) | |
raise 'must have attributes like %w[id created_at]' unless attributes.is_a? Array | |
# 엑셀에서 csv 파일을 열었을 때 utf8을 사용하도록 BOM 표식 추가 | |
head = 'EF BB BF'.split(' ').map{ |a| a.hex.chr }.join() | |
CSV.generate(csv = head) do |csv| | |
csv << attributes | |
all.each do |row| | |
if block_given? | |
yield row | |
else | |
csv << attributes.map{ |attr| row.send(attr) } | |
end | |
end | |
end | |
end | |
end | |
ActiveRecord::Base.send :extend, ExportToCsv |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment