2017-04-05 68 views
0

如何清理这一点?我想摆脱不必要的代码,像所有的重复a.question == f.question比较我每个case语句中使用:如何避免case 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

记住红宝石让你在几个简单的传球做这些事情。有没有必要做这一切一气呵成:

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 

另一个速战速决是两个条款,有相同的代码相结合。

您可以通过在Answer模型上编写一个==方法来更轻松地进行比较。

+2

“...在你的Answer模型上写一个'=='方法,可以为你做比较”。是。这可以使代码的可读性发生很大的变化。 –

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