ruby-on-rails - 如何将 3 个 ServiceObjects 最小化为每 1 个操作 1 个
问题描述
我有一个带有一些代码和 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
解决方案
制作很多 ServiceObject 是可以的。他们每个人都应该解决 1 个问题。即使我们每 1 个控制器或每 1 个动作有很多 SObject。
我知道了 :)
推荐阅读
- python - 使用 BeautifulSoup 和网络抓取来自动填写网络表单
- android - 如何防止android sqlite数据库中的重复数据?
- android - 程序类型已经存在:com.google.android.gms.common.util.VisibleForTesting
- javafx - 在 GridPane 中放置 JavaFX 自定义控件
- javascript - jQuery 切换在动画之后起作用,但在动画之前不起作用
- c# - 值不能为空。C#
- javascript - 在 React 中,使用引导模式如何编辑和更新状态?
- c++ - c++ 中的堆栈实现,没有最大堆栈大小限制
- python - 将原始日期格式转换为 pandas 日期对象
- mongodb - 在 Ubuntu Snap 安装上更改默认 MongoDB 端口