11module Question
22 class Selection < QuestionBase
33 attribute :selection
4+ attribute :none_of_the_above_answer
5+
6+ before_validation :clear_none_of_the_above_answer_if_not_selected
7+
48 validates :selection , presence : true
59 validate :selection , :validate_checkbox , if : :allow_multiple_answers?
610 validate :selection , :validate_radio , unless : :allow_multiple_answers?
11+ validates :none_of_the_above_answer , length : { maximum : 499 }
12+
13+ with_options unless : :autocomplete_component? do
14+ validates :none_of_the_above_answer , presence : true , if : :validate_none_of_the_above_answer_presence?
15+ end
716
817 def allow_multiple_answers?
918 answer_settings . only_one_option != "true"
@@ -42,8 +51,20 @@ def selection_options_with_none_of_the_above
4251 [ *options , none_of_the_above_option ]
4352 end
4453
54+ def autocomplete_component?
55+ answer_settings . selection_options . count > 30
56+ end
57+
58+ def has_none_of_the_above_question?
59+ none_of_the_above_question . present?
60+ end
61+
4562 private
4663
64+ def clear_none_of_the_above_answer_if_not_selected
65+ self . none_of_the_above_answer = nil unless none_of_the_above_selected?
66+ end
67+
4768 def allowed_options
4869 selection_options_with_none_of_the_above . map ( &:name )
4970 end
@@ -68,5 +89,23 @@ def validate_checkbox
6889
6990 errors . add ( :selection , :inclusion ) if selection_without_blanks . any? { |item | allowed_options . exclude? ( item ) }
7091 end
92+
93+ def validate_none_of_the_above_answer_presence?
94+ none_of_the_above_question . present? && none_of_the_above_question . is_optional != "true" && none_of_the_above_selected?
95+ end
96+
97+ def none_of_the_above_question
98+ return nil unless is_optional?
99+ return nil unless answer_settings . respond_to? ( :none_of_the_above_question )
100+ return nil unless answer_settings . none_of_the_above_question . respond_to? ( :question_text )
101+
102+ answer_settings . none_of_the_above_question
103+ end
104+
105+ def none_of_the_above_selected?
106+ return selection_without_blanks . include? ( I18n . t ( "page.none_of_the_above" ) ) if allow_multiple_answers?
107+
108+ selection == I18n . t ( "page.none_of_the_above" )
109+ end
71110 end
72111end
0 commit comments