我有一个带有一些代码和 3 个服务对象调用的操作的 Worker。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