LoginSignup
7
6

More than 5 years have passed since last update.

Railsのmodels/concernsにCSV出力用のModuleを置くと検証に便利

Posted at

app/models/concerns/exportable.rb

module Exportable
  extend ActiveSupport::Concern

  included do
    extend  ClassMethods
    include InstanceMethods
  end


  module ClassMethods

    def export_csv!(file_path = Rails.root.join("tmp/csv/#{model_name.plural}/#{Time.current.strftime('%Y%m%d%H%M')}.csv"))
      FileUtils::mkdir_p(file_path.dirname)
      File.open(file_path, 'w') do |f|
        f.puts generate_csv
      end

      file_path
    end


    def generate_csv
      CSV.generate do |csv|
        csv << column_names
        all.each do |r|
          csv << r.attributes.values_at(*column_names)
        end
      end
    end
  end



  module InstanceMethods

  end
end

というのを用意。カラムは全部出力される

class Item < ActiveRecord::Base
  include Exportable
end
Item.where(created_at: Date.today.all_month).export_csv!

だとcreated_atが今月のItemの一覧が /tmp/csv/items/xxx.csv に出力される。
whereやscopeで条件を絞ってデータを見たいとき便利

7
6
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
7
6