summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLin Jen-Shin <godfat@godfat.org>2017-11-17 21:25:49 +0800
committerLin Jen-Shin <godfat@godfat.org>2017-11-18 01:01:53 +0800
commit7441c7af9acb849ba5f6a25895614fe5cc8023b2 (patch)
treeb987741c38ec964592df29a4cf6d90eeac420566
parent9ac0c76b78cd04b2505924f003dd720a0f155959 (diff)
downloadgitlab-ce-7441c7af9acb849ba5f6a25895614fe5cc8023b2.tar.gz
Allow initialize method and single ivar
-rw-r--r--rubocop/cop/module_with_instance_variables.rb20
-rw-r--r--spec/rubocop/cop/module_with_instance_variables_spec.rb29
2 files changed, 46 insertions, 3 deletions
diff --git a/rubocop/cop/module_with_instance_variables.rb b/rubocop/cop/module_with_instance_variables.rb
index 95e612b58e8..974a23bf701 100644
--- a/rubocop/cop/module_with_instance_variables.rb
+++ b/rubocop/cop/module_with_instance_variables.rb
@@ -46,14 +46,18 @@ module RuboCop
def check_method_definition(node)
node.each_child_node(:def) do |definition|
# We allow this pattern:
- # def f
- # @f ||= true
- # end
+ #
+ # def f
+ # @f ||= true
+ # end
if only_ivar_or_assignment?(definition)
# We don't allow if any other ivar is used
definition.each_descendant(:ivar) do |offense|
add_offense(offense, :expression)
end
+ # We allow initialize method and single ivar
+ elsif initialize_method?(definition) || single_ivar?(definition)
+ next
else
definition.each_descendant(:ivar, :ivasgn) do |offense|
add_offense(offense, :expression)
@@ -68,6 +72,16 @@ module RuboCop
definition.child_nodes.size == 2 &&
node.or_asgn_type? && node.child_nodes.first.ivasgn_type?
end
+
+ def single_ivar?(definition)
+ node = definition.child_nodes.last
+
+ definition.child_nodes.size == 2 && node.ivar_type?
+ end
+
+ def initialize_method?(definition)
+ definition.children.first == :initialize
+ end
end
end
end
diff --git a/spec/rubocop/cop/module_with_instance_variables_spec.rb b/spec/rubocop/cop/module_with_instance_variables_spec.rb
index bac39117dba..72f6b01aa81 100644
--- a/spec/rubocop/cop/module_with_instance_variables_spec.rb
+++ b/spec/rubocop/cop/module_with_instance_variables_spec.rb
@@ -137,6 +137,35 @@ describe RuboCop::Cop::ModuleWithInstanceVariables do
it_behaves_like 'not registering offense'
end
+ context 'when source is using simple ivar' do
+ let(:source) do
+ <<~RUBY
+ module M
+ def f?
+ @f
+ end
+ end
+ RUBY
+ end
+
+ it_behaves_like 'not registering offense'
+ end
+
+ context 'when source is defining initialize' do
+ let(:source) do
+ <<~RUBY
+ module M
+ def initialize
+ @a = 1
+ @b = 2
+ end
+ end
+ RUBY
+ end
+
+ it_behaves_like 'not registering offense'
+ end
+
context 'when source is using simple or ivar assignment with other ivar' do
let(:source) do
<<~RUBY