Module: SqlEnum::ClassMethods

Defined in:
lib/sql_enum/class_methods.rb

Instance Method Summary collapse

Instance Method Details

#sql_enum(column_name, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/sql_enum/class_methods.rb', line 3

def sql_enum(column_name, options = {})
  # skip redefinitions
  return if defined_enums.key?(column_name.to_s)

  # Query values
  enum_column = EnumColumn.new(table_name, column_name)
  values_map = enum_column.values.to_h { |value| [value.to_sym, value.to_s] }

  # Check option defaults
  prefix = options.fetch(:_prefix, !!SqlEnum.configuration&.default_prefix)
  suffix = options.fetch(:_suffix, !!SqlEnum.configuration&.default_suffix)

  # Define enum using Rails enum
  enum(column_name, values_map, prefix: prefix, suffix: suffix)

  # Override reader to return symbols
  col_name = column_name.to_s
  enum_type = ->(subtype) do
    subtype = subtype.subtype if ActiveRecord::Enum::EnumType === subtype
    EnumType.new(col_name, send(col_name.pluralize), subtype)
  end

  if respond_to?(:decorate_attributes, true)
    decorate_attributes([col_name]) { |_name, subtype| enum_type.call(subtype) }
  else
    attribute(column_name, &enum_type)
  end

  prefix_str = format_affix(column_name, prefix, suffix: '_')
  suffix_str = format_affix(column_name, suffix, prefix: '_')

  # Fix query methods to compare symbols to symbols
  values_map.each_value do |value|
    method_name = "#{prefix_str}#{value}#{suffix_str}?"
    define_method(method_name) { self[column_name] == value.to_sym }
  end
end