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
-
#pg_enum(column_name, options = {}) ⇒ Object
Define a PostgreSQL enum type.
-
#pg_enum_values(column_name) ⇒ Array
Retrieve the acceptable values for the enum type associated with the given column.
Instance Method Details
#pg_enum(column_name, options = {}) ⇒ Object
Define a PostgreSQL enum type.
By default, setting an enum attribute to an unregistered value results in an exception being raised. You can disable this feature by setting the option :exceptions to false when registering the enum:
=> pg_enum :size, exceptions: false
35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/enum_kit/active_record_patches/enum.rb', line 35 def pg_enum(column_name, = {}) values = pg_enum_values(column_name).map { |v| [v.to_sym, v.to_s] } enum(column_name => Hash[values]) enum = type_for_attribute(column_name) raise 'Expected an ActiveRecord::Enum::EnumType' unless enum.is_a?(ActiveRecord::Enum::EnumType) enum.disable_exceptions = .key?(:exceptions) && ![:exceptions] nil end |
#pg_enum_values(column_name) ⇒ Array
Retrieve the acceptable values for the enum type associated with the given column.
14 15 16 17 18 19 20 21 22 23 24 |
# File 'lib/enum_kit/active_record_patches/enum.rb', line 14 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 |