From 561304aefb2e6c026b8544c33919c0ef83d0f831 Mon Sep 17 00:00:00 2001 From: viralpraxis Date: Tue, 24 Sep 2024 19:29:05 +0300 Subject: [PATCH] Add `AllowedIdentifiers` configuration option --- config/default.yml | 1 + .../modules/ROOT/pages/cops_threadsafety.adoc | 4 ++++ .../rack_middleware_instance_variable.rb | 7 ++++-- .../rack_middleware_instance_variable_spec.rb | 23 +++++++++++++++++++ 4 files changed, 33 insertions(+), 2 deletions(-) diff --git a/config/default.yml b/config/default.yml index 046e130..bb4af3c 100644 --- a/config/default.yml +++ b/config/default.yml @@ -44,3 +44,4 @@ ThreadSafety/RackMiddlewareInstanceVariable: - 'lib/middleware/**/*.rb' - 'app/middlewares/**/*.rb' - 'lib/middlewares/**/*.rb' + AllowedIdentifiers: [] diff --git a/docs/modules/ROOT/pages/cops_threadsafety.adoc b/docs/modules/ROOT/pages/cops_threadsafety.adoc index 1c03497..7f354cd 100644 --- a/docs/modules/ROOT/pages/cops_threadsafety.adoc +++ b/docs/modules/ROOT/pages/cops_threadsafety.adoc @@ -333,4 +333,8 @@ end | Include | `+app/middleware/**/*.rb+`, `+lib/middleware/**/*.rb+`, `+app/middlewares/**/*.rb+`, `+lib/middlewares/**/*.rb+` | Array + +| AllowedIdentifiers +| `[]` +| Array |=== diff --git a/lib/rubocop/cop/thread_safety/rack_middleware_instance_variable.rb b/lib/rubocop/cop/thread_safety/rack_middleware_instance_variable.rb index 1d13fa1..621d08e 100644 --- a/lib/rubocop/cop/thread_safety/rack_middleware_instance_variable.rb +++ b/lib/rubocop/cop/thread_safety/rack_middleware_instance_variable.rb @@ -44,6 +44,7 @@ module ThreadSafety # end # end class RackMiddlewareInstanceVariable < Base + include AllowedIdentifiers include OperationWithThreadsafeResult MSG = 'Avoid instance variables in Rack middleware.' @@ -68,8 +69,10 @@ def on_class(node) node.each_node(:def) do |method_definition_node| method_definition_node.each_node(:ivasgn, :ivar) do |ivar_node| - assignable, = ivar_node.to_a - next if assignable == application_variable || safe_variables.include?(assignable) + variable, = ivar_node.to_a + if variable == application_variable || safe_variables.include?(variable) || allowed_identifier?(variable) + next + end add_offense ivar_node end diff --git a/spec/rubocop/cop/thread_safety/rack_middleware_instance_variable_spec.rb b/spec/rubocop/cop/thread_safety/rack_middleware_instance_variable_spec.rb index f40df36..c1ede4a 100644 --- a/spec/rubocop/cop/thread_safety/rack_middleware_instance_variable_spec.rb +++ b/spec/rubocop/cop/thread_safety/rack_middleware_instance_variable_spec.rb @@ -316,4 +316,27 @@ def call(env) RUBY end end + + context 'with non-empty `AllowedIdentifiers` config' do + let(:cop_config) do + { 'AllowedIdentifiers' => ['options'] } + end + + it 'registers an offense' do + expect_offense(<<~RUBY) + class TestMiddleware + def call(env) + @app.call(env) + end + + def initialize(app) + @app = app + @some_var = 2 + ^^^^^^^^^^^^^ #{msg} + @options = 1 + end + end + RUBY + end + end end