class ActiveRecord::PostgresEnum::EnumValidator

Public Class Methods

enum_values(attr_id, type, connection) click to toggle source
# File lib/active_record/postgres_enum/enum_validator.rb, line 6
def self.enum_values(attr_id, type, connection)
  @enums ||= {}
  return @enums[attr_id] if @enums.key?(attr_id)

  @enums[attr_id] ||= connection.enums.fetch(type.to_sym) do
    raise "Enum `#{type}` not found in a database #{connection}"
  end
end

Public Instance Methods

validate_each(object, attribute, value) click to toggle source
# File lib/active_record/postgres_enum/enum_validator.rb, line 15
def validate_each(object, attribute, value)
  enum_type = enum_type(object, attribute)
  attr_id = "#{object.class.name}##{attribute}"

  return if self.class.enum_values(attr_id, enum_type, object.class.connection).include?(value)

  object.errors.add(
    attribute,
    options[:message] || :invalid_enum_value,
    value: value,
    type: enum_type
  )
end

Private Instance Methods

enum_type(object, attribute) click to toggle source
# File lib/active_record/postgres_enum/enum_validator.rb, line 31
def enum_type(object, attribute)
  object.class.columns_hash[attribute.to_s].sql_type
end