From ab898457cf724d22e3b09d9b49e180105ede5453 Mon Sep 17 00:00:00 2001 From: Benjamin Quorning Date: Wed, 15 Jul 2020 11:37:19 +0200 Subject: [PATCH] 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 995b4fe5f16cd73feb2625eadd0fad236cfab38e and adds memoization in a class instance variable. --- lib/rubocop/cop/rspec/base.rb | 44 +++++++++++++---------------------- 1 file changed, 16 insertions(+), 28 deletions(-) diff --git a/lib/rubocop/cop/rspec/base.rb b/lib/rubocop/cop/rspec/base.rb index 1df17d4af..3ced15657 100644 --- a/lib/rubocop/cop/rspec/base.rb +++ b/lib/rubocop/cop/rspec/base.rb @@ -21,14 +21,6 @@ class Base < ::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:disable Lint/MissingSuper RuboCop::Cop::Base.inherited(subclass) @@ -41,32 +33,28 @@ def relevant_file?(file) private def relevant_rubocop_rspec_file?(file) - rspec_pattern.match?(file) + self.class.rspec_pattern.match?(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