Class: Bureaucrat::Fields::TypedChoiceField

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=, #default_error_messages, #default_widget, #initialize_copy, #valid_value?

Methods inherited from Field

#bound_data, #clean, #default_error_messages, #default_hidden_widget, #default_validators, #default_widget, #initialize_copy, #populate_object, #prepare_value, #run_validators, #widget_attrs

Constructor Details

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

Returns a new instance of TypedChoiceField.



587
588
589
590
591
592
# File 'lib/bureaucrat/fields.rb', line 587

def initialize(choices=[], options={})
  @coerce = options.delete(:coerce) || lambda{|val| val}
  @empty_value = options.fetch(:empty_value, '')
  options.delete(:empty_value)
  super(choices, options)
end

Instance Method Details

#original_validateObject



611
# File 'lib/bureaucrat/fields.rb', line 611

alias_method :original_validate, :validate

#to_object(value) ⇒ Object



594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
# File 'lib/bureaucrat/fields.rb', line 594

def to_object(value)
  value = super(value)
  original_validate(value)

  if value == @empty_value || Validators.empty_value?(value)
    return @empty_value
  end

  begin
    @coerce.call(value)
  rescue TypeError, ValidationError
    msg = Utils.format_string(error_messages[:invalid_choice],
                              value: value)
    raise ValidationError.new(msg)
  end
end

#validate(value) ⇒ Object



613
614
# File 'lib/bureaucrat/fields.rb', line 613

def validate(value)
end