Sha256: e704ec8a2109532dc6c25cd1624c1ca6682e4a608f016df03bd41c39887057a6

Contents?: true

Size: 1.04 KB

Versions: 2

Compression:

Stored size: 1.04 KB

Contents

# frozen_string_literal: true

# :nodoc:
#
module ActiveRecord
  # :nodoc:
  #
  module Enum
    # Retrieve the acceptable values for the enum type associated with the given column.
    #
    # @param  column_name [String, Symbol] The name of a column representing an enum.
    # @return             [Array]          The acceptable values for the enum type associated with the column.
    #
    def pg_enum_values(column_name)
      type = columns_hash[column_name.to_s]&.sql_type

      raise "Unable to determine '#{table_name}.#{column_name}' type. Did you forget to db:migrate?" if type.blank?

      enums = connection.enums[type.to_sym]

      raise "Unable to retrieve enums for type '#{type}'. Did you forget to db:migrate?" if enums.nil?

      enums
    end

    # Define a PostgreSQL enum type.
    #
    # @param column_name [String, Symbol] The name of a column representing an enum.
    #
    def pg_enum(column_name)
      values = pg_enum_values(column_name).map { |v| [v.to_sym, v.to_s] }
      enum(column_name => Hash[values])
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
enum_kit-0.3.1 lib/enum_kit/active_record_patches/enum.rb
enum_kit-0.3.0 lib/enum_kit/active_record_patches/enum.rb