Class: Exwiw::SchemaGenerator

Inherits:
Object
  • Object
show all
Defined in:
lib/exwiw/schema_generator.rb

Defined Under Namespace

Classes: MultipleDatabasesNotSupportedError

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(models:, output_dir:) ⇒ SchemaGenerator

Returns a new instance of SchemaGenerator.



15
16
17
18
# File 'lib/exwiw/schema_generator.rb', line 15

def initialize(models:, output_dir:)
  @models = models
  @output_dir = output_dir
end

Class Method Details

.from_rails_application(output_dir:) ⇒ Object



10
11
12
13
# File 'lib/exwiw/schema_generator.rb', line 10

def self.from_rails_application(output_dir:)
  Rails.application.eager_load!
  new(models: ActiveRecord::Base.descendants, output_dir: output_dir)
end

Instance Method Details

#build_tablesObject



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/exwiw/schema_generator.rb', line 26

def build_tables
  models = concrete_models
  validate_single_database!(models)

  models.group_by(&:table_name).map do |table_name, model_group|
    representative = model_group.first
    TableConfig.from_symbol_keys(
      name: table_name,
      primary_key: representative.primary_key,
      belongs_tos: aggregate_belongs_tos(model_group),
      columns: representative.column_names.map { |name| { name: name } },
    )
  end
end

#generate!Object



20
21
22
23
24
# File 'lib/exwiw/schema_generator.rb', line 20

def generate!
  tables = build_tables
  write_files(tables)
  tables
end

#write_files(tables) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/exwiw/schema_generator.rb', line 41

def write_files(tables)
  FileUtils.mkdir_p(@output_dir)

  tables.each do |table|
    path = File.join(@output_dir, "#{table.name}.json")
    config_to_write =
      if File.exist?(path)
        TableConfig.from(JSON.parse(File.read(path))).merge(table)
      else
        table
      end
    File.write(path, JSON.pretty_generate(config_to_write.to_hash) + "\n")
  end
end