app/models/active_fields/field/enum.rb in active_fields-0.2.0 vs app/models/active_fields/field/enum.rb in active_fields-1.0.0

- old
+ new

@@ -1,15 +1,22 @@ # frozen_string_literal: true module ActiveFields module Field class Enum < ActiveFields.config.field_base_class + acts_as_active_field( + validator: { + class_name: "ActiveFields::Validators::EnumValidator", + options: -> { { required: required?, allowed_values: allowed_values } }, + }, + caster: { + class_name: "ActiveFields::Casters::EnumCaster", + }, + ) + store_accessor :options, :required, :allowed_values - # attribute :required, :boolean, default: false - # attribute :allowed_values, :string, array: true, default: [] - validates :required, exclusion: [nil] validate :validate_allowed_values %i[required].each do |column| define_method(column) do @@ -38,18 +45,30 @@ private def validate_allowed_values if allowed_values.nil? errors.add(:allowed_values, :blank) - elsif allowed_values.is_a?(Array) - if allowed_values.empty? - errors.add(:allowed_values, :blank) - elsif allowed_values.any? { !_1.is_a?(String) } + return false + end + + unless allowed_values.is_a?(Array) + errors.add(:allowed_values, :invalid) + return false + end + + if allowed_values.empty? + errors.add(:allowed_values, :blank) + return false + end + + allowed_values.each do |value_element| + if value_element.blank? errors.add(:allowed_values, :invalid) + return false end - else - errors.add(:allowed_values, :invalid) end + + true end def set_defaults self.required ||= false self.allowed_values ||= []