LoginSignup
2
4

More than 3 years have passed since last update.

[ruby]バッチ処理について

Posted at

バッチ処理とは?

バッチ処理とは“一定量の(あるいは一定期間の)データを集め、一括処理するための処理方法”

私は、大量のデータを処理すること全般をイメージしてる。

引用元
https://www.imkk.jp/blog/what-is-batch-processing.html

バッチ処理のフロー

私の業務では、DBに一括登録するデータをスプレッドシートから取り組むバッチ処理でした。
以下では、データベースに商品を一括にスプレッドシートから取り込んで追加するという場合。

フローは以下の通り
まずrakeファイルにそのバッチ処理がどういったものなのかをdescにかく。
そのあと走らせる。
以下がそのコード

import_new_products_information.rake
namespace :batch do
    desc '新規商品の追加'
    task import_new_products_information: :environment do
        require 'batches/import_new_products_information'
        Batches::ImportNewProductsInformation.run
    end
end

走らせるファイル。
一応シート内に商品名と商品コードというカラムがあることが前提。

import_new_products_informations.rb
require 'batch/base'
require 'google_spreadsheet'

module Batches
  class ImportrProductsInformations < Batch::Base
    SPREADSHEET_KEY = '追加する商品のスプレッドシートキー'.freeze
    SHEET_NAME = '追加する商品一覧があるシートの名前 例)取り込み用など'.freeze

    def execute(_args)
      gs = GoogleSpreadsheet.new(SPREADSHEET_KEY)

      gs.spreadsheet.worksheet_by_title(SHEET_NAME).tap do |sheet|
        sheet.list.each do |row|
          products_informations.create!(
            product_name: row['商品名'],
            product_number: row['商品コード']
          )
        end
      end
    end
  end
end
google_spredsheet.rb
def worksheet_by_title(sheet_name)
    spreadsheet.worksheet_by_title(sheet_name)
 end
2
4
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
4