Sha256: da8fe61762d7fd337f969871799d3b62cc83b60b7974b9a5fa2b6fcfe0f501b3

Contents?: true

Size: 1004 Bytes

Versions: 6

Compression:

Stored size: 1004 Bytes

Contents

# frozen_string_literal: true

# :nodoc:
#
module ActiveRecord
  # :nodoc:
  #
  module Validations
    # Validates whether an enum's value is acceptable by comparing with the acceptable values defined in the PostgreSQL
    # database.
    #
    class PgEnumValidator < ActiveModel::EachValidator
      # Validate the given value is acceptable for the enum.
      #
      # @param record    [ActiveRecord::Base]  The record being validated.
      # @param attribute [Symbol]              The enum attribute being validated.
      # @param value     [String, Symbol, nil] The current value of the enum.
      #
      def validate_each(record, attribute, value)
        values = record.class.pg_enum_values(attribute)

        return if values.include?(value)

        record.errors.add(attribute, options[:message] || :invalid, **options.except(:message).merge!(
          attribute: record.class.human_attribute_name(attribute),
          values: values.join(', ')
        ))
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
enum_kit-0.3.1 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb
enum_kit-0.3.0 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb
enum_kit-0.2.3 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb
enum_kit-0.2.2 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb
enum_kit-0.2.1 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb
enum_kit-0.1.0 lib/enum_kit/active_record_patches/validations/pg_enum_validator.rb