Skip to content

Commit

Permalink
Optimize Cop#relevant_rubocop_rspec_file?
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
bquorning committed Jul 15, 2020
1 parent 1be4c09 commit b809f3a
Showing 1 changed file with 16 additions and 28 deletions.
44 changes: 16 additions & 28 deletions lib/rubocop/cop/rspec/cop.rb
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,6 @@ class Cop < ::RuboCop::Cop::Base
include RuboCop::RSpec::Language
include RuboCop::RSpec::Language::NodePattern

DEFAULT_CONFIGURATION =
RuboCop::RSpec::CONFIG.fetch('AllCops').fetch('RSpec')

DEFAULT_PATTERN_RE = Regexp.union(
DEFAULT_CONFIGURATION.fetch('Patterns')
.map(&Regexp.public_method(:new))
)

# Invoke the original inherited hook so our cops are recognized
def self.inherited(subclass)
RuboCop::Cop::Cop.inherited(subclass)
Expand All @@ -41,32 +33,28 @@ def relevant_file?(file)
private

def relevant_rubocop_rspec_file?(file)
rspec_pattern =~ file
self.class.rspec_pattern =~ file
end

def rspec_pattern
if rspec_pattern_config?
Regexp.union(rspec_pattern_config.map(&Regexp.public_method(:new)))
else
DEFAULT_PATTERN_RE
class << self
def rspec_pattern
@rspec_pattern ||=
Regexp.union(
rspec_pattern_config.map(&Regexp.public_method(:new))
)
end
end

def all_cops_config
config
.for_all_cops
end
private

def rspec_pattern_config?
return unless all_cops_config.key?('RSpec')
def rspec_pattern_config
default_configuration =
RuboCop::RSpec::CONFIG.fetch('AllCops').fetch('RSpec')

all_cops_config.fetch('RSpec').key?('Patterns')
end

def rspec_pattern_config
all_cops_config
.fetch('RSpec', DEFAULT_CONFIGURATION)
.fetch('Patterns')
Config.new
.for_all_cops
.fetch('RSpec', default_configuration)
.fetch('Patterns')
end
end
end
end
Expand Down

0 comments on commit b809f3a

Please sign in to comment.