LoginSignup
2
3

More than 5 years have passed since last update.

とりあえず Rails の DB の内容をサクッと CSV 出力したいときのためのコード

Posted at

コード

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>
2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3