-
Notifications
You must be signed in to change notification settings - Fork 539
Expand file tree
/
Copy pathcontroller_generator.rb
More file actions
62 lines (52 loc) · 1.5 KB
/
controller_generator.rb
File metadata and controls
62 lines (52 loc) · 1.5 KB
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
module Jsonapi
class ControllerGenerator < Rails::Generators::NamedBase
source_root File.expand_path('../templates', __FILE__)
class_option :base_controller, type: :string, default: 'JSONAPI::ResourceController'
class_option :skip_routes, type: :boolean, desc: "Don't add routes to config/routes.rb."
def create_resource
template_file = File.join(
'app/controllers',
class_path,
"#{file_name.pluralize}_controller.rb"
)
template 'controller.rb.tt', template_file
end
def add_routes
return if options[:skip_routes]
route generate_routing_code
end
private
def base_controller
options['base_controller']
end
# This method creates nested route entry for namespaced resources.
# For eg. rails g controller foo/bar/baz index show
# Will generate -
# namespace :foo do
# namespace :bar do
# get 'baz/index'
# get 'baz/show'
# end
# end
def generate_routing_code
depth = 0
lines = []
# Create 'namespace' ladder
# namespace :foo do
# namespace :bar do
regular_class_path.each do |ns|
lines << indent("namespace :#{ns} do\n", depth * 2)
depth += 1
end
lines << indent(%{jsonapi_resources :#{file_name.pluralize}\n}, depth * 2)
# Create `end` ladder
# end
# end
until depth.zero?
depth -= 1
lines << indent("end\n", depth * 2)
end
lines.join
end
end
end