我正在编写一个脚本,使用 ClassroomDAL 中包含的方法多次调用我们的数据库 (postgres)。这些数据库调用的输出然后用于扩充 summaryData 哈希。
但是 - 我觉得我正在创造大量的重复并且不确定如何解决。非常感谢任何建议!
summaryData = {}
adaptiveQuestions = ClassroomDAL.adaptiveQuestions(conn, district_ids_postgres, options.start_date, options.end_date)
targetedQuestions = ClassroomDAL.targetedQuestions(conn, district_ids_postgres, options.start_date, options.end_date)
daysSpent = ClassroomDAL.daysSpent(conn, district_ids_postgres, options.start_date, options.end_date)
getKSsDistrict = ClassroomDAL.getKSsDistrict(conn, district_ids_postgres, options.start_date, options.end_date)
addStudentStats(summaryData, adaptiveQuestions, ["math_questions"])
addStudentStats(summaryData, targetedQuestions, ["math_questions"])
addStudentStats(summaryData, targetedQuestions, ["math_days", "classroom_grade"])
addGradeLevelStats(summaryData, getKSsDistrict)
最佳答案
对于重复的参数,你可以使用 Array splat:
args = [conn, district_ids_postgres, options.start_date, options.end_date]
#then
adaptiveQuestions = ClassroomDAL.adaptiveQuestions *args
targetedQuestions = ClassroomDAL.targetedQuestions *args
daysSpent = ClassroomDAL.daysSpent *args
getKSsDistrict = ClassroomDAL.getKSsDistrict *args
然后您可以尝试通过循环和发送使事情变得更智能:
adaptiveQuestions, targetedQuestions, daysSpent, getKSsDistrict = ['adaptiveQuestions', 'targetedQuestions', 'daysSpent', 'getKSsDistrict'].each.map do |method|
ClassroomDAL.send(method, *args)
end
附言
- 代码未经测试
- 有时,更智能的语法可读性不是很好!这是一个权衡
- 你应该在 Ruby 中使用蛇形大小写而不是驼峰大小写,即
days_spent 而不是
daysSpent
关于ruby - 重构以减少重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40435259/