我该如何清理一下?我想摆脱不必要的代码,就像我在每个a.question == f.question
语句中使用的所有重复case
比较一样:
def notifications_lookup(filters, answers)
filters.flat_map do |f|
answers.select do |a|
case a.question.question_type
when "image"
a.question == f.question && a.answer_image.image_id == f.answer.to_i
when "single"
a.question == f.question && a.choice_answer.choice_id == f.answer.to_i
when "list"
a.question == f.question && a.choice_answer.choice_id == f.answer.to_i
when "multiple"
a.question == f.question && !(f.answer.split(",").map(&:to_i) & a.answer_multiple.choices.map(&:id)).empty?
when "rating"
results = verify_condition(f, a)
a.question == f.question && results.any?
else
a.question == f.question
end
end
end
end
def verify_condition(filter, a)
a.answer_raitings.map do |r|
r.raiting == filter.raiting && filter.answer.split(",").map(&:to_i).include?(r.response)
end
end
答案 0 :(得分:0)
您可以只选择a.question == f.question
,然后可以在进一步选择中使用该选择的结果。
def notifications_lookup(filters, answers)
filters.flat_map do |f|
selected_answers = answers.select {|a| a.question == f.question}
selected_answers = selected_answers.select do |a|
case a.question.question_type
when "image"
a.answer_image.image_id == f.answer.to_i
when "single"
a.choice_answer.choice_id == f.answer.to_i
when "list"
a.choice_answer.choice_id == f.answer.to_i
when "multiple"
!(f.answer.split(",").map(&:to_i) & a.answer_multiple.choices.map(&:id)).empty?
when "rating"
results = verify_condition(f, a)
results.any?
else
true
end
end
end
end
答案 1 :(得分:0)
记住Ruby允许你在几个简单的过程中做这些事情。没有必要一气呵成:
def notifications_lookup(filters, answers)
filters.flat_map do |f|
answers.select do |a|
a.question == f.question
end.select do |a|
case a.question.question_type
when "image"
a.answer_image.image_id == f.answer.to_i
when "single", "list"
a.choice_answer.choice_id == f.answer.to_i
when "multiple"
!(f.answer.split(",").map(&:to_i) & a.answer_multiple.choices.map(&:id)).empty?
when "rating"
verify_condition(f, a).any?
else
true
end
end
end
end
另一个快速解决方法是组合两个具有相同代码的子句。
您可以通过在答案模型上编写==
方法,让您更轻松地进行比较。