Sha256: 199ae6359a013a2357a30fdef73b6c4562bf5e027ba54dabf69076d3e0cdb186

Contents?: true

Size: 1.29 KB

Versions: 3

Compression:

Stored size: 1.29 KB

Contents

# frozen_string_literal: true

module ActiveRecordDataLoader
  module ActiveRecord
    class EnumValueGenerator
      class << self
        def generator_for(model_class:, ar_column:, connection_factory:)
          values = enum_values_for(ar_column.sql_type, connection_factory)
          -> { values.sample }
        end

        private

        def enum_values_for(enum_type, connection_factory)
          connection = connection_factory.call

          if connection.adapter_name.downcase.to_sym == :postgresql
            postgres_enum_values_for(connection, enum_type)
          elsif connection.adapter_name.downcase.to_s.start_with?("mysql")
            mysql_enum_values_for(enum_type)
          else
            []
          end
        ensure
          connection&.close
        end

        def postgres_enum_values_for(connection, enum_type)
          connection
            .execute("SELECT unnest(enum_range(NULL::#{enum_type}))::text")
            .map(&:values)
            .flatten
            .compact
        end

        def mysql_enum_values_for(enum_type)
          enum_type
            .to_s
            .downcase
            .gsub(/\Aenum\(|\)\Z/, "")
            .split(",")
            .map(&:strip)
            .map { |s| s.gsub(/\A'|'\Z/, "") }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
active_record_data_loader-1.3.1 lib/active_record_data_loader/active_record/enum_value_generator.rb
active_record_data_loader-1.3.0 lib/active_record_data_loader/active_record/enum_value_generator.rb
active_record_data_loader-1.2.0 lib/active_record_data_loader/active_record/enum_value_generator.rb