Class: Bureaucrat::Fields::ChoiceField

Inherits:
Field
  • Object
show all
Defined in:
lib/bureaucrat/fields.rb

Direct Known Subclasses

MultipleChoiceField, TypedChoiceField

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 Field

#bound_data, #clean, #default_hidden_widget, #default_validators, #populate_object, #prepare_value, #run_validators, #widget_attrs

Constructor Details

#initialize(choices = [], options = {}) ⇒ ChoiceField

Returns a new instance of ChoiceField.



522
523
524
525
526
# File 'lib/bureaucrat/fields.rb', line 522

def initialize(choices=[], options={})
  options[:required] = options.fetch(:required, true)
  super(options)
  self.choices = choices
end

Instance Method Details

#choicesObject



541
542
543
# File 'lib/bureaucrat/fields.rb', line 541

def choices
  @choices
end

#choices=(value) ⇒ Object



545
546
547
# File 'lib/bureaucrat/fields.rb', line 545

def choices=(value)
  @choices = @widget.choices = value
end

#default_error_messagesObject



533
534
535
# File 'lib/bureaucrat/fields.rb', line 533

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

#default_widgetObject



537
538
539
# File 'lib/bureaucrat/fields.rb', line 537

def default_widget
  Widgets::Select
end

#initialize_copy(original) ⇒ Object



528
529
530
531
# File 'lib/bureaucrat/fields.rb', line 528

def initialize_copy(original)
  super(original)
  self.choices = original.choices.dup
end

#to_object(value) ⇒ Object



549
550
551
552
553
554
555
# File 'lib/bureaucrat/fields.rb', line 549

def to_object(value)
  if Validators.empty_value?(value)
    ''
  else
    value.to_s
  end
end

#valid_value?(value) ⇒ Boolean

Returns:

  • (Boolean)


567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
# File 'lib/bureaucrat/fields.rb', line 567

def valid_value?(value)
  @choices.each do |k, v|
    if v.is_a?(Array)
      # This is an optgroup, so look inside the group for options
      v.each do |k2, v2|
        return true if value == k2.to_s
      end
    elsif k.is_a?(Hash)
      # this is a hash valued choice list
      return true if value == k[:value].to_s
    else
      return true if value == k.to_s
    end
  end

  false
end

#validate(value) ⇒ Object



557
558
559
560
561
562
563
564
565
# File 'lib/bureaucrat/fields.rb', line 557

def validate(value)
  super(value)

  unless !value || Validators.empty_value?(value) || valid_value?(value)
    msg = Utils.format_string(error_messages[:invalid_choice],
                              value: value)
    raise ValidationError.new(msg)
  end
end