2017-04-05 13 views
0

これを少しきれいにするにはどうしたらいいですか?私は、各case文で私が使用しているすべての繰り返しa.question == f.questionの比較などの不要なコードを取り除きたい:ケースステートメント内の繰り返し条件を回避する方法

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 

もう1つの簡単な修正は、同じコードを持つ2つの句を結合することでした。

あなたの回答モデルに==メソッドを書き込むことで、これをさらに簡単に行うことができます。

+2

"...あなたのための比較を行うことができるあなたの答えモデルに' == 'メソッドを書くこと。はい。これは、コードの可読性に大きな違いをもたらす可能性があります。 –

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 
関連する問題