重构更少的重复

时间:2016-11-05 05:57:04

标签: ruby postgresql

我正在编写一个脚本,该脚本使用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)

1 个答案:

答案 0 :(得分:1)

对于重复的参数,您可以使用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

P.Ss

  • 未经过测试的代码
  • 有时候,更聪明的语法不是非常易读!这是一个权衡
  • 你应该在Ruby中使用蛇案而不是骆驼案,即days_spent instead daysSpent