0

いくつかのコードとサービス オブジェクトの 3 つの呼び出しを含むアクションを持つワーカーがあります。オブジェクト保存のさまざまな状態 (更新開始、更新完了) 中にデータをベースに保存するための 2 つのサービス オブジェクト。そして、進行状況のパーセンテージをカウントするための 1。

1 アクションあたり 1 サービス オブジェクトである必要があります。オーバーヘッド サービス オブジェクトの使用を避けるにはどうすればよいですか? または、コードをパーツに分割するなど、コードをどのようにリファクタリングする必要がありますか?

質問スタイルに誤りがありましたら申し訳ありません。私は状況を明確に説明しようとしていました。

csv_worker.rb

def perform(import_id)

  ...

  @import = Import.find(import_id)

  ImportStartedUpdateJobService.call(@import)  

  users = []  
  row_hash = {}
  result = ''

  CSV.foreach(@import.file.path, headers: true).with_index do |row, index|
    row_hash = row.to_h
    row_hash['import_id'] = @import.id

    # The day is put on the first place
    # to make the data valid for saving in DB
    row_hash = make_the_date_valid(row_hash)    

    user = User.new(row_hash)

    if user.valid?
      ...
    end

    @import.percentage = ImportPercentageUpdateJobService.call(@import)
    @import.save if (index % 10).zero? 

    if (index % 1000).zero? 
      User.import(users)
      users = []
    end  
  end  

  User.import(users)
  ImportCompletedUpdateJobService.call(@import)

  puts 
end    

import_started_update_job_service.rb

def initialize(import)
  @import = import
end

def call
  @import.count_of_lines_in_csv = CSV.read(@import.file.path).count - 1
  @import.started_at            = Time.now
  @import.import_status         = 'started'
  @import.save
end

import_completed_update_job_service.rb

...
def call
  @import.completed_at  = Time.now
  @import.import_status = 'completed'
  @import.percentage = 100
  @import.save
end

import_percentage_update_job_service.rb

...
def call
  @import.percentage = if @import.count_of_lines_in_csv.positive?
                         (@import.count_of_created_users +
                          @import.count_of_not_created_users).to_f /
                           @import.count_of_lines_in_csv *
                           100
                       end

  @import.percentage.to_i  
end
4

1 に答える 1