Class: Bureaucrat::Fields::MultipleChoiceField

Inherits:
ChoiceField show all
Defined in:
lib/bureaucrat/fields.rb

Instance Attribute Summary

Attributes inherited from Field

#error_messages, #help_text, #hidden_widget, #initial, #label, #required, #show_hidden_initial, #validators, #widget

Instance Method Summary collapse

Methods inherited from ChoiceField

#choices, #choices=, #initialize, #initialize_copy, #valid_value?

Methods inherited from Field

#bound_data, #clean, #default_validators, #initialize, #initialize_copy, #populate_object, #prepare_value, #run_validators, #widget_attrs

Constructor Details

This class inherits a constructor from Bureaucrat::Fields::ChoiceField

Instance Method Details

#default_error_messagesObject



618
619
620
621
# File 'lib/bureaucrat/fields.rb', line 618

def default_error_messages
  super.merge(invalid_choice: 'Select a valid choice. %(value)s is not one of the available choices.',
              invalid_list: 'Enter a list of values.')
end

#default_hidden_widgetObject



627
628
629
# File 'lib/bureaucrat/fields.rb', line 627

def default_hidden_widget
  Widgets::MultipleHiddenInput
end

#default_widgetObject



623
624
625
# File 'lib/bureaucrat/fields.rb', line 623

def default_widget
  Widgets::SelectMultiple
end

#to_object(value) ⇒ Object



631
632
633
634
635
636
637
638
639
# File 'lib/bureaucrat/fields.rb', line 631

def to_object(value)
  if !value || Validators.empty_value?(value)
    []
  elsif !value.is_a?(Array)
    raise ValidationError.new(error_messages[:invalid_list])
  else
    value.map(&:to_s)
  end
end

#validate(value) ⇒ Object



641
642
643
644
645
646
647
648
649
650
651
652
653
# File 'lib/bureaucrat/fields.rb', line 641

def validate(value)
  if required && (!value || Validators.empty_value?(value))
    raise ValidationError.new(error_messages[:required])
  end

  value.each do |val|
    unless valid_value?(val)
      msg = Utils.format_string(error_messages[:invalid_choice],
                                value: val)
      raise ValidationError.new(msg)
    end
  end
end