Module: ActiveRecord::Enum

Defined in:
lib/enum_kit/active_record_patches/enum.rb,
lib/enum_kit/active_record_patches/enum/enum_type.rb

Overview

:nodoc:

Defined Under Namespace

Classes: EnumType

Instance Method Summary collapse

Instance Method Details

#pg_enum(name, options = {}) ⇒ Object

Define a PostgreSQL enum type.

Parameters:

  • name (String)

    The name of an enum column.

  • options (Hash) (defaults to: {})

    The options.



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/enum_kit/active_record_patches/enum.rb', line 27

def pg_enum(name, options = {})
  values = pg_enum_values(name).map { |value| [value.to_sym, value.to_s] }

  enum(name => Hash[values])

  enum = type_for_attribute(name)

  raise 'Expected an ActiveRecord::Enum::EnumType' unless enum.is_a?(ActiveRecord::Enum::EnumType)

  enum.disable_exceptions = options.key?(:exceptions) && !options[:exceptions]

  nil
end

#pg_enum_values(name) ⇒ Array

Retrieve the acceptable values for the enum type associated with the given column.

Parameters:

  • The (String, Symbol)

    name of an enum column.

Returns:

  • (Array)

    The acceptable values for the enum type associated with the column.



14
15
16
17
18
19
20
# File 'lib/enum_kit/active_record_patches/enum.rb', line 14

def pg_enum_values(name)
  # Determine the PostgreSQL type for the enum.
  type = columns_hash[name.to_s].sql_type

  # Query the PostgreSQL database for the enum's acceptable values.
  connection.enums[type.to_sym]
end