コード
class ExportCsv
attr_reader :model, :dir
# 第 1 引数に出力したいモデル、第 2 引数に出力先のディレクトリを指定する。
def self.call(model, dir)
new(model, dir).call
end
def initialize(model, dir)
@model = model
@dir = Pathname(dir)
end
def call
filepath.open('w:SJIS') do |f|
f.puts(csv_string)
end
filepath
end
private
def csv_string
options = { headers: headers, write_headers: true, force_quotes: true }
CSV.generate(options) do |csv|
model.find_each do |record|
csv << record.attributes.values
end
end
end
def filepath
dir / filename
end
def filename
"#{model.table_name}_#{Time.zone.now.strftime('%Y%m%d%H%M%S')}.csv"
end
def headers
model.column_names
end
end
使用例
上記のクラスを定義した上で、Rails コンソールで次のコードを実行する。
ExportCsv.call(Girl, '/Users/quanon/Downloads')
# => #<Pathname:/Users/quanon/Downloads/girls_20181126185252.csv>