forked from thoughtbot/administrate
/
routes_generator.rb
96 lines (77 loc) · 2.5 KB
/
routes_generator.rb
1
2
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
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
if defined?(Zeitwerk)
Zeitwerk::Loader.eager_load_all
else
Rails.application.eager_load!
end
require "rails/generators/base"
require "administrate/namespace"
module Administrate
module Generators
class RoutesGenerator < Rails::Generators::Base
source_root File.expand_path("../templates", __FILE__)
class_option :namespace, type: :string, default: "admin"
def insert_dashboard_routes
if should_route_dashboard?
route(dashboard_routes)
end
end
def warn_about_invalid_models
invalid_dashboard_models.each do |model|
puts "WARNING: Unable to generate a dashboard for #{model}."
if namespaced_models.include?(model)
puts " - Administrate does not yet support namespaced models."
end
if models_without_tables.include?(model)
puts " - It is not connected to a database table."
puts " Make sure your database migrations are up to date."
end
end
unnamed_constants.each do |invalid_model|
puts "NOTICE: Skipping dynamically generated model #{invalid_model}."
end
end
private
def namespace
options[:namespace]
end
def dashboard_resources
valid_dashboard_models.map do |model|
model.to_s.pluralize.underscore
end
end
def valid_dashboard_models
database_models - invalid_dashboard_models
end
def database_models
ActiveRecord::Base.descendants.reject(&:abstract_class?)
end
def invalid_dashboard_models
(models_without_tables + namespaced_models + unnamed_constants).uniq
end
def models_without_tables
database_models.reject(&:table_exists?)
end
def namespaced_models
database_models.select { |model| model.to_s.include?("::") }
end
def unnamed_constants
ActiveRecord::Base.descendants.reject { |d| d.name == d.to_s }
end
def dashboard_routes
ERB.new(File.read(routes_file_path)).result(binding)
end
def routes_includes_resources?
File.read(rails_routes_file_path).include?(dashboard_routes)
end
def rails_routes_file_path
Rails.root.join("config/routes.rb")
end
def routes_file_path
File.expand_path(find_in_source_paths("routes.rb.erb"))
end
def should_route_dashboard?
routes_includes_resources? || valid_dashboard_models.any?
end
end
end
end