Skip to content

Commit b809f3a

Browse files
committed
Optimize Cop#relevant_rubocop_rspec_file?
The result of `rspec_pattern` is always the same (because it is based on the configuration file), so there is no need to re-calculate it every time it is called. I tried memozing on the Cop instance, but at least when running the specs, we instantiate Cop way too often. Memoizing on the class level reduces the number of calculations to once per `Cop` subclass we have. If we allowed using class variables (`@@rspec_pattern`) we could reduce the number of calculations to one. This commit reverts 995b4fe and adds memoization in a class instance variable.
1 parent 1be4c09 commit b809f3a

File tree

1 file changed

+16
-28
lines changed

1 file changed

+16
-28
lines changed

lib/rubocop/cop/rspec/cop.rb

Lines changed: 16 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,6 @@ class Cop < ::RuboCop::Cop::Base
2121
include RuboCop::RSpec::Language
2222
include RuboCop::RSpec::Language::NodePattern
2323

24-
DEFAULT_CONFIGURATION =
25-
RuboCop::RSpec::CONFIG.fetch('AllCops').fetch('RSpec')
26-
27-
DEFAULT_PATTERN_RE = Regexp.union(
28-
DEFAULT_CONFIGURATION.fetch('Patterns')
29-
.map(&Regexp.public_method(:new))
30-
)
31-
3224
# Invoke the original inherited hook so our cops are recognized
3325
def self.inherited(subclass)
3426
RuboCop::Cop::Cop.inherited(subclass)
@@ -41,32 +33,28 @@ def relevant_file?(file)
4133
private
4234

4335
def relevant_rubocop_rspec_file?(file)
44-
rspec_pattern =~ file
36+
self.class.rspec_pattern =~ file
4537
end
4638

47-
def rspec_pattern
48-
if rspec_pattern_config?
49-
Regexp.union(rspec_pattern_config.map(&Regexp.public_method(:new)))
50-
else
51-
DEFAULT_PATTERN_RE
39+
class << self
40+
def rspec_pattern
41+
@rspec_pattern ||=
42+
Regexp.union(
43+
rspec_pattern_config.map(&Regexp.public_method(:new))
44+
)
5245
end
53-
end
5446

55-
def all_cops_config
56-
config
57-
.for_all_cops
58-
end
47+
private
5948

60-
def rspec_pattern_config?
61-
return unless all_cops_config.key?('RSpec')
49+
def rspec_pattern_config
50+
default_configuration =
51+
RuboCop::RSpec::CONFIG.fetch('AllCops').fetch('RSpec')
6252

63-
all_cops_config.fetch('RSpec').key?('Patterns')
64-
end
65-
66-
def rspec_pattern_config
67-
all_cops_config
68-
.fetch('RSpec', DEFAULT_CONFIGURATION)
69-
.fetch('Patterns')
53+
Config.new
54+
.for_all_cops
55+
.fetch('RSpec', default_configuration)
56+
.fetch('Patterns')
57+
end
7058
end
7159
end
7260
end

0 commit comments

Comments
 (0)