Class: Brick::ModelsGenerator

Inherits:
Rails::Generators::Base
  • Object
show all
Includes:
FancyGets
Defined in:
lib/generators/brick/models_generator.rb

Overview

Auto-generates models, controllers, or views

Instance Method Summary collapse

Instance Method Details

#brick_modelsObject



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/generators/brick/models_generator.rb', line 16

def brick_models
  # %%% If Apartment is active and there's no schema_to_analyse, ask which schema they want

  ::Brick.mode = :on
  ActiveRecord::Base.establish_connection

  # Load all models
  ::Brick.eager_load_classes

  # Generate a list of viable models that can be chosen
  longest_length = 0
  model_info = Hash.new { |h, k| h[k] = {} }
  tableless = Hash.new { |h, k| h[k] = [] }
  existing_models = ActiveRecord::Base.descendants.reject do |m|
    m.abstract_class? || !m.table_exists? || ::Brick.relations.key?(m.table_name)
  end
  models = ::Brick.relations.keys.each_with_object([]) do |tbl, s|
    next if tbl.is_a?(Symbol)

    tbl_parts = tbl.split('.')
    tbl_parts.shift if [::Brick.default_schema, 'public'].include?(tbl_parts.first)
    tbl_parts[-1] = tbl_parts[-1].singularize
    s << tbl_parts.join('/').camelize
  end - existing_models.map(&:name)
  models.sort! do |a, b| # Sort first to separate namespaced stuff from the rest, then alphabetically
    is_a_namespaced = a.include?('::')
    is_b_namespaced = b.include?('::')
    if is_a_namespaced && !is_b_namespaced
      1
    elsif !is_a_namespaced && is_b_namespaced
      -1
    else
      a <=> b
    end
  end
  models.each do |m| # Find longest name in the list for future use to show lists on the right side of the screen
    if longest_length < (len = m.length)
      longest_length = len
    end
  end
  chosen = gets_list(list: models, chosen: models.dup)
  relations = ::Brick.relations
  chosen.each do |model_name|
    # %%% If we're in a schema then make sure the module file exists
    base_module = if (model_parts = model_name.split('::')).length > 1
                    "::#{model_parts.first}".constantize
                  else
                    Object
                  end
    _built_model, code = Object.send(:build_model, relations, base_module, base_module.name, model_parts.last)
    path = ['models']
    path.concat(model_parts.map(&:underscore))
    dir = +"#{::Rails.root}/app"
    path[0..-2].each do |path_part|
      dir << "/#{path_part}"
      Dir.mkdir(dir) unless Dir.exist?(dir)
    end
    File.open("#{dir}/#{path.last}.rb", 'w') { |f| f.write code } unless code.blank?
  end
  puts "\n*** Created #{chosen.length} model files under app/models ***"
end