discourse/migrations/lib/database/schema/enum_writer.rb
Gerhard Schlager 89f26da39d
MT: Switch to nested module style across migrations/ (#38564)
Ruby's compact module syntax (`module
Migrations::Database::Schema::DSL`) breaks lexical constant lookup —
`Module.nesting` only includes the innermost constant, so every
cross-module reference must be fully qualified. In practice this means
writing `Migrations::Database::Schema::Helpers` even when you're already
inside `Migrations::Database::Schema`.

Nested module definitions restore the full nesting chain, which brings
several practical benefits:

- **Less verbose code**: references like `Schema::Helpers`,
`Database::IntermediateDB`, or `Converters::Base::ProgressStep` work
without repeating the full path from root
- **Easier to write new code**: contributors don't need to remember
which prefixes are required — if you're inside the namespace, short
names just work
- **Fewer aliasing workarounds**: removes the need for constants like
`MappingType = Migrations::Importer::MappingType` that existed solely to
shorten references
- **Standard Ruby style**: consistent with how most Ruby projects and
gems structure their namespaces

The diff is large but mechanical — no logic changes, just module
wrapping and shortening references that the nesting now resolves.
Generated code (intermediate_db models/enums) keeps fully qualified
references like `Migrations::Database.format_*` since it must work
regardless of the configured output namespace.

- Convert 138 lib files from compact to nested module definitions
- Remove now-redundant fully qualified prefixes and aliases
- Update model and enum writers to generate nested modules with correct
indentation
- Regenerate all intermediate_db models and enums
2026-03-19 18:15:19 +01:00

60 lines
1.6 KiB
Ruby
Vendored

# frozen_string_literal: true
module Migrations
module Database
module Schema
class EnumWriter
def initialize(namespace, header)
@namespace = namespace
@header = header.gsub(/^/, "# ")
@namespace_parts = namespace.split("::")
@base_indent = " " * (@namespace_parts.size - 1)
end
def self.filename_for(enum)
"#{enum.name.downcase.underscore}.rb"
end
def output_enum(enum, output_stream)
@out = output_stream
module_name = Helpers.to_singular_classname(enum.name)
emit "# frozen_string_literal: true"
emit
emit @header
emit
@namespace_parts.each { |part| emit "module #{part}" }
emit " module #{module_name}"
emit " extend Migrations::Enum"
emit
emit enum_values(enum.values)
(@namespace_parts.size + 1).times { emit " end" }
ensure
@out = nil
end
private
def emit(text = nil)
if text.nil?
@out.puts
else
text.each_line(chomp: true) do |line|
@out.puts(line.empty? ? "" : "#{@base_indent}#{line}")
end
end
end
def enum_values(values)
values
.sort_by { |_k, v| v }
.map do |name, value|
value = %Q|"#{value}"| if value.is_a?(String)
" #{Helpers.to_const_name(name)} = #{value}"
end
.join("\n")
end
end
end
end
end