@@ -32,13 +32,22 @@ module RSpec
32
32
# # good
33
33
# whatever_spec.rb # describe MyClass, type: :routing do; end
34
34
#
35
+ # @example `UseActiveSupportInflections: true`
36
+ # # Enable to use ActiveSupport's inflector for custom acronyms
37
+ # # like HTTP, etc. Set to false by default.
38
+ # # The InflectorPath provides the path to the inflector file.
39
+ # # The default is ./config/initializers/inflections.rb.
40
+ #
35
41
class SpecFilePathFormat < Base
36
42
include TopLevelGroup
37
43
include Namespace
38
44
include FileHelp
39
45
40
46
MSG = 'Spec path should end with `%<suffix>s`.'
41
47
48
+ # Class instance variable to cache ActiveSupport availability
49
+ @activesupport_available = nil
50
+
42
51
# @!method example_group_arguments(node)
43
52
def_node_matcher :example_group_arguments , <<~PATTERN
44
53
(block $(send #rspec? #ExampleGroups.all $_ $...) ...)
@@ -57,6 +66,28 @@ def on_top_level_example_group(node)
57
66
end
58
67
end
59
68
69
+ # For testing and debugging
70
+ def self . reset_activesupport_cache!
71
+ @activesupport_available = nil
72
+ end
73
+
74
+ def self . activesupport_inflections_available? ( inflections )
75
+ return @activesupport_available unless @activesupport_available . nil?
76
+
77
+ @activesupport_available = begin
78
+ return false unless File . exist? ( inflections )
79
+
80
+ require 'active_support/inflector'
81
+ require inflections
82
+
83
+ true
84
+ rescue LoadError , NameError
85
+ false
86
+ end
87
+ rescue StandardError
88
+ false
89
+ end
90
+
60
91
private
61
92
62
93
def ensure_correct_file_path ( send_node , class_name , arguments )
@@ -106,10 +137,29 @@ def expected_path(constant)
106
137
end
107
138
108
139
def camel_to_snake_case ( string )
109
- string
110
- . gsub ( /([^A-Z])([A-Z]+)/ , '\1_\2' )
111
- . gsub ( /([A-Z])([A-Z][^A-Z\d ]+)/ , '\1_\2' )
112
- . downcase
140
+ if activesupport_inflections_available?
141
+ ActiveSupport ::Inflector . underscore ( string )
142
+ else
143
+ string
144
+ . gsub ( /([^A-Z])([A-Z]+)/ , '\1_\2' )
145
+ . gsub ( /([A-Z])([A-Z][^A-Z\d ]+)/ , '\1_\2' )
146
+ . downcase
147
+ end
148
+ end
149
+
150
+ def inflector_path
151
+ cop_config . fetch ( 'InflectorPath' ,
152
+ './config/initializers/inflections.rb' )
153
+ end
154
+
155
+ def activesupport_inflections_available?
156
+ return false unless use_activesupport_inflections?
157
+
158
+ self . class . activesupport_inflections_available? ( inflector_path )
159
+ end
160
+
161
+ def use_activesupport_inflections?
162
+ cop_config . fetch ( 'UseActiveSupportInflections' , false )
113
163
end
114
164
115
165
def custom_transform
0 commit comments