我有这个代码块,其中每个下一组行都取决于先前的响应,并且步骤集必须遵循固定的路径,使其略微有状态。
这导致我的方法增加大量代码并重复代码(即使变量和数据不同)。我怎样才能干掉这段代码?
def process
response = ServiceResponse.new(false, [])
# Step 1
project_path = import_project()
if project_path.present?
response.data << Step.new('import', true, "Project imported")
send_realtime_data(response)
hr_config, hr_config_error = fetch_hr_config(project_path)
weighted_scores_config, ws_error = fetch_weighted_scores(project_path)
if hr_config.blank?
response.data << Step.new('.hr_config.yml', false, hr_config_error || "Empty configuration file")
return response
else
response.data << Step.new('.hr_config.yml', true, 'Configuration file found')
send_realtime_data(response)
end
if weighted_scores_config.blank? && ws_error.present?
response.data << Step.new('.hr_weighted_scores.yml', false, ws_error)
return response
else
response.data << Step.new('.hr_weighted_scores.yml', true, "Weighted scoring config found")
send_realtime_data(response)
end
configuration = ::X::FullStack::Configuration.new(
hr_config, {weighted_scores: weighted_scores_config}
)
if !configuration.valid?
response.data << Step.new('validate_configuration', false, "Configuration validation failed", configuration.validations.as_json)
return response
else
response.data << Step.new('validate_configuration', false, "Configuration validated successfully", configuration.validations.as_json)
send_realtime_data(response)
end
#....
end
end
通过websocket共享对此方法的响应(代码来自rails延迟任务),send_realtime_data
方法将数据发送到前端。当方法结束时(通过return
),任务完成,返回值被发送到前端,然后关闭websocket。
答案 0 :(得分:0)
您的else
分支机构是多余的。
def process
response = ServiceResponse.new(false, [])
project_path = import_project
if project_path.blank?
return
end
response.data << Step.new('import', true, "Project imported")
send_realtime_data(response)
hr_config, hr_config_error = fetch_hr_config(project_path)
weighted_scores_config, ws_error = fetch_weighted_scores(project_path)
if hr_config.blank?
response.data << Step.new('.hr_config.yml', false, hr_config_error || "Empty configuration file")
return response
end
response.data << Step.new('.hr_config.yml', true, 'Configuration file found')
send_realtime_data(response)
if weighted_scores_config.blank? && ws_error.present?
response.data << Step.new('.hr_weighted_scores.yml', false, ws_error)
return response
end
response.data << Step.new('.hr_weighted_scores.yml', true, "Weighted scoring config found")
send_realtime_data(response)
configuration = ::X::FullStack::Configuration.new(
hr_config, {weighted_scores: weighted_scores_config}
)
unless configuration.valid?
response.data << Step.new('validate_configuration', false, "Configuration validation failed", configuration.validations.as_json)
return response
end
response.data << Step.new('validate_configuration', false, "Configuration validated successfully", configuration.validations.as_json)
send_realtime_data(response)
#....
end