Skip to content

Commit d89ddef

Browse files
authored
Refactor AnnotateRoutes by adding AnnotateRoutes::HeaderGenerator (#790)
I noticed that `AnnotateRoutes` can be more maintainable by refactoring. I am planning to refactor `AnnotateRoutes` in this order. * separate logic of `AnnotateRoutes` into `AnnotateRoutes::HeaderGenerator`. * add methods to `AnnotateRoutes::HeaderGenerator` and refactor methods. * add `AnnotateRoutes::AnnotationProcessor` and `AnnotateRoutes::RemovalProcessor` The final goal of this refactoring is as follows. * https://github.com/nard-tech/annotate_models/blob/feature/refactor_annotate_routes/processors/lib/annotate/annotate_routes.rb * https://github.com/nard-tech/annotate_models/tree/feature/refactor_annotate_routes/processors/lib/annotate/annotate_routes So in the first I added `AnnotateRoutes::HeaderGenerator` in order to separate logic of `AnnotateRoutes` in this PR. When refactor of `AnnotateRoutes` is finished, I would like to refactor `AnnotateModels` in a like way.
1 parent d9392d9 commit d89ddef

File tree

4 files changed

+112
-91
lines changed

4 files changed

+112
-91
lines changed

.rubocop_todo.yml

+12-13
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# This configuration was generated by
22
# `rubocop --auto-gen-config`
3-
# on 2020-03-01 03:15:48 +0900 using RuboCop version 0.68.1.
3+
# on 2020-04-03 00:51:53 +0900 using RuboCop version 0.68.1.
44
# The point is for the user to remove these configuration records
55
# one by one as the offenses are removed from the code base.
66
# Note that changes in the inspected code, or installation of new
@@ -163,12 +163,11 @@ Lint/InheritException:
163163
Exclude:
164164
- 'lib/annotate/annotate_models.rb'
165165

166-
# Offense count: 2
166+
# Offense count: 1
167167
# Configuration parameters: MaximumRangeSize.
168168
Lint/MissingCopEnableDirective:
169169
Exclude:
170170
- 'lib/annotate/annotate_models.rb'
171-
- 'lib/annotate/annotate_routes.rb'
172171

173172
# Offense count: 2
174173
Lint/RescueException:
@@ -213,7 +212,7 @@ Naming/AccessorMethodName:
213212
Exclude:
214213
- 'lib/annotate.rb'
215214

216-
# Offense count: 103
215+
# Offense count: 102
217216
# Configuration parameters: Blacklist.
218217
# Blacklist: (?-mix:(^|\s)(EO[A-Z]{1}|END)(\s|$))
219218
Naming/HeredocDelimiterNaming:
@@ -235,12 +234,13 @@ Naming/UncommunicativeMethodParamName:
235234
Exclude:
236235
- 'Rakefile'
237236

238-
# Offense count: 1
237+
# Offense count: 2
239238
# Configuration parameters: EnforcedStyle.
240239
# SupportedStyles: inline, group
241240
Style/AccessModifierDeclarations:
242241
Exclude:
243242
- 'lib/annotate/annotate_models.rb'
243+
- 'lib/annotate/annotate_routes/header_generator.rb'
244244

245245
# Offense count: 1
246246
Style/CaseEquality:
@@ -266,7 +266,7 @@ Style/Dir:
266266
Exclude:
267267
- 'bin/annotate'
268268

269-
# Offense count: 9
269+
# Offense count: 10
270270
Style/Documentation:
271271
Exclude:
272272
- 'spec/**/*'
@@ -275,6 +275,7 @@ Style/Documentation:
275275
- 'lib/annotate/active_record_patch.rb'
276276
- 'lib/annotate/annotate_models.rb'
277277
- 'lib/annotate/annotate_routes.rb'
278+
- 'lib/annotate/annotate_routes/header_generator.rb'
278279
- 'lib/annotate/annotate_routes/helpers.rb'
279280
- 'lib/annotate/version.rb'
280281
- 'lib/generators/annotate/install_generator.rb'
@@ -293,14 +294,13 @@ Style/ExpandPathArguments:
293294
Exclude:
294295
- 'annotate.gemspec'
295296

296-
# Offense count: 10
297+
# Offense count: 9
297298
# Cop supports --auto-correct.
298299
# Configuration parameters: EnforcedStyle.
299300
# SupportedStyles: format, sprintf, percent
300301
Style/FormatString:
301302
Exclude:
302303
- 'lib/annotate/annotate_models.rb'
303-
- 'lib/annotate/annotate_routes.rb'
304304

305305
# Offense count: 23
306306
# Configuration parameters: EnforcedStyle.
@@ -309,7 +309,7 @@ Style/FormatStringToken:
309309
Exclude:
310310
- 'lib/annotate/annotate_models.rb'
311311

312-
# Offense count: 27
312+
# Offense count: 28
313313
# Cop supports --auto-correct.
314314
# Configuration parameters: EnforcedStyle.
315315
# SupportedStyles: when_needed, always, never
@@ -338,7 +338,7 @@ Style/IfUnlessModifier:
338338
- 'Rakefile'
339339
- 'bin/annotate'
340340
- 'lib/annotate/annotate_models.rb'
341-
- 'lib/annotate/annotate_routes.rb'
341+
- 'lib/annotate/annotate_routes/header_generator.rb'
342342

343343
# Offense count: 1
344344
# Cop supports --auto-correct.
@@ -432,15 +432,14 @@ Style/RedundantSelf:
432432
Exclude:
433433
- 'lib/tasks/annotate_models_migrate.rake'
434434

435-
# Offense count: 13
435+
# Offense count: 12
436436
# Cop supports --auto-correct.
437437
# Configuration parameters: EnforcedStyle, AllowInnerSlashes.
438438
# SupportedStyles: slashes, percent_r, mixed
439439
Style/RegexpLiteral:
440440
Exclude:
441441
- 'Rakefile'
442442
- 'lib/annotate/annotate_models.rb'
443-
- 'lib/annotate/annotate_routes.rb'
444443

445444
# Offense count: 1
446445
# Cop supports --auto-correct.
@@ -521,7 +520,7 @@ Style/UnneededPercentQ:
521520
Exclude:
522521
- 'annotate.gemspec'
523522

524-
# Offense count: 377
523+
# Offense count: 375
525524
# Cop supports --auto-correct.
526525
# Configuration parameters: AutoCorrect, AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, IgnoredPatterns.
527526
# URISchemes: http, https

lib/annotate/annotate_routes.rb

+2-77
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,3 @@
1-
# rubocop:disable Metrics/ModuleLength
2-
31
# == Annotate Routes
42
#
53
# Based on:
@@ -21,18 +19,15 @@
2119
#
2220

2321
require_relative './annotate_routes/helpers'
22+
require_relative './annotate_routes/header_generator'
2423

2524
module AnnotateRoutes
26-
PREFIX = '== Route Map'.freeze
27-
PREFIX_MD = '## Route Map'.freeze
28-
HEADER_ROW = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action'].freeze
29-
3025
class << self
3126
def do_annotations(options = {})
3227
if routes_file_exist?
3328
existing_text = File.read(routes_file)
3429
content, header_position = Helpers.strip_annotations(existing_text)
35-
new_content = annotate_routes(header(options), content, header_position, options)
30+
new_content = annotate_routes(HeaderGenerator.generate(options), content, header_position, options)
3631
new_text = new_content.join("\n")
3732

3833
if rewrite_contents(existing_text, new_text)
@@ -71,49 +66,6 @@ def routes_file
7166
@routes_rb ||= File.join('config', 'routes.rb')
7267
end
7368

74-
def header(options = {})
75-
routes_map = app_routes_map(options)
76-
77-
magic_comments_map, routes_map = Helpers.extract_magic_comments_from_array(routes_map)
78-
79-
out = []
80-
81-
magic_comments_map.each do |magic_comment|
82-
out << magic_comment
83-
end
84-
out << '' if magic_comments_map.any?
85-
86-
out << comment(options[:wrapper_open]) if options[:wrapper_open]
87-
88-
out << comment(options[:format_markdown] ? PREFIX_MD : PREFIX) + (options[:timestamp] ? " (Updated #{Time.now.strftime('%Y-%m-%d %H:%M')})" : '')
89-
out << comment
90-
return out if routes_map.size.zero?
91-
92-
maxs = [HEADER_ROW.map(&:size)] + routes_map[1..-1].map { |line| line.split.map(&:size) }
93-
94-
if options[:format_markdown]
95-
max = maxs.map(&:max).compact.max
96-
97-
out << comment(content(HEADER_ROW, maxs, options))
98-
out << comment(content(['-' * max, '-' * max, '-' * max, '-' * max], maxs, options))
99-
else
100-
out << comment(content(routes_map[0], maxs, options))
101-
end
102-
103-
out += routes_map[1..-1].map { |line| comment(content(options[:format_markdown] ? line.split(' ') : line, maxs, options)) }
104-
out << comment(options[:wrapper_close]) if options[:wrapper_close]
105-
106-
out
107-
end
108-
109-
def comment(row = '')
110-
if row == ''
111-
'#'
112-
else
113-
"# #{row}"
114-
end
115-
end
116-
11769
def strip_on_removal(content, header_position)
11870
if header_position == :before
11971
content.shift while content.first == ''
@@ -162,32 +114,5 @@ def annotate_routes(header, content, header_position, options = {})
162114

163115
new_content
164116
end
165-
166-
def app_routes_map(options)
167-
routes_map = `rake routes`.chomp("\n").split(/\n/, -1)
168-
169-
# In old versions of Rake, the first line of output was the cwd. Not so
170-
# much in newer ones. We ditch that line if it exists, and if not, we
171-
# keep the line around.
172-
routes_map.shift if routes_map.first =~ /^\(in \//
173-
174-
# Skip routes which match given regex
175-
# Note: it matches the complete line (route_name, path, controller/action)
176-
if options[:ignore_routes]
177-
routes_map.reject! { |line| line =~ /#{options[:ignore_routes]}/ }
178-
end
179-
180-
routes_map
181-
end
182-
183-
def content(line, maxs, options = {})
184-
return line.rstrip unless options[:format_markdown]
185-
186-
line.each_with_index.map do |elem, index|
187-
min_length = maxs.map { |arr| arr[index] }.max || 0
188-
189-
sprintf("%-#{min_length}.#{min_length}s", elem.tr('|', '-'))
190-
end.join(' | ')
191-
end
192117
end
193118
end
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,97 @@
1+
require_relative './helpers'
2+
3+
module AnnotateRoutes
4+
class HeaderGenerator
5+
PREFIX = '== Route Map'.freeze
6+
PREFIX_MD = '## Route Map'.freeze
7+
HEADER_ROW = ['Prefix', 'Verb', 'URI Pattern', 'Controller#Action'].freeze
8+
9+
class << self
10+
def generate(options = {})
11+
routes_map = app_routes_map(options)
12+
new(options, routes_map).generate
13+
end
14+
15+
private :new
16+
17+
private
18+
19+
def app_routes_map(options)
20+
routes_map = `rake routes`.chomp("\n").split(/\n/, -1)
21+
22+
# In old versions of Rake, the first line of output was the cwd. Not so
23+
# much in newer ones. We ditch that line if it exists, and if not, we
24+
# keep the line around.
25+
routes_map.shift if routes_map.first =~ %r{^\(in \/}
26+
27+
# Skip routes which match given regex
28+
# Note: it matches the complete line (route_name, path, controller/action)
29+
if options[:ignore_routes]
30+
routes_map.reject! { |line| line =~ /#{options[:ignore_routes]}/ }
31+
end
32+
33+
routes_map
34+
end
35+
end
36+
37+
def initialize(options, routes_map)
38+
@options = options
39+
@routes_map = routes_map
40+
end
41+
42+
def generate
43+
magic_comments_map, contents_without_magic_comments = Helpers.extract_magic_comments_from_array(routes_map)
44+
45+
out = []
46+
47+
magic_comments_map.each do |magic_comment|
48+
out << magic_comment
49+
end
50+
out << '' if magic_comments_map.any?
51+
52+
out << comment(options[:wrapper_open]) if options[:wrapper_open]
53+
54+
out << comment(options[:format_markdown] ? PREFIX_MD : PREFIX) + (options[:timestamp] ? " (Updated #{Time.now.strftime('%Y-%m-%d %H:%M')})" : '')
55+
out << comment
56+
return out if contents_without_magic_comments.size.zero?
57+
58+
maxs = [HEADER_ROW.map(&:size)] + contents_without_magic_comments[1..-1].map { |line| line.split.map(&:size) }
59+
60+
if options[:format_markdown]
61+
max = maxs.map(&:max).compact.max
62+
63+
out << comment(content(HEADER_ROW, maxs))
64+
out << comment(content(['-' * max, '-' * max, '-' * max, '-' * max], maxs))
65+
else
66+
out << comment(content(contents_without_magic_comments[0], maxs))
67+
end
68+
69+
out += contents_without_magic_comments[1..-1].map { |line| comment(content(options[:format_markdown] ? line.split(' ') : line, maxs)) }
70+
out << comment(options[:wrapper_close]) if options[:wrapper_close]
71+
72+
out
73+
end
74+
75+
private
76+
77+
attr_reader :options, :routes_map
78+
79+
def comment(row = '')
80+
if row == ''
81+
'#'
82+
else
83+
"# #{row}"
84+
end
85+
end
86+
87+
def content(line, maxs)
88+
return line.rstrip unless options[:format_markdown]
89+
90+
line.each_with_index.map do |elem, index|
91+
min_length = maxs.map { |arr| arr[index] }.max || 0
92+
93+
format("%-#{min_length}.#{min_length}s", elem.tr('|', '-'))
94+
end.join(' | ')
95+
end
96+
end
97+
end

spec/lib/annotate/annotate_routes_spec.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@
4949
expect(File).to receive(:exist?).with(ROUTE_FILE).and_return(true).once
5050
expect(File).to receive(:read).with(ROUTE_FILE).and_return(route_file_content).once
5151

52-
expect(AnnotateRoutes).to receive(:`).with('rake routes').and_return(rake_routes_result).once
52+
expect(AnnotateRoutes::HeaderGenerator).to receive(:`).with('rake routes').and_return(rake_routes_result).once
5353
end
5454

5555
context 'When the result of `rake routes` is present' do

0 commit comments

Comments
 (0)