Skip to content

Commit

Permalink
Better error messages for MemoizedInstanceVariableName cop
Browse files Browse the repository at this point in the history
  • Loading branch information
Satyajit Phanse authored and bbatsov committed Mar 3, 2018
1 parent 1a9b8c8 commit 900ae13
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 7 deletions.
10 changes: 8 additions & 2 deletions lib/rubocop/cop/naming/memoized_instance_variable_name.rb
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ module Naming
# end
#
class MemoizedInstanceVariableName < Cop
MSG = 'Memoized variable does not match method name.'.freeze
MSG = 'Memoized variable `%<var>s` does not match ' \
'method name `%<method>s`. Use `@%<method>s` instead.'.freeze

def self.node_pattern
memo_assign = '(or_asgn $(ivasgn _) _)'
Expand All @@ -51,7 +52,12 @@ def self.node_pattern
def on_def(node)
(method_name, ivar_assign) = memoized?(node)
return if matches?(method_name, ivar_assign)
add_offense(node, location: ivar_assign.source_range)
msg = format(
MSG,
var: ivar_assign.children.first.to_s,
method: method_name
)
add_offense(node, location: ivar_assign.source_range, message: msg)
end
alias on_defs on_def

Expand Down
10 changes: 5 additions & 5 deletions spec/rubocop/cop/naming/memoized_instance_variable_name_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
expect_offense(<<-RUBY.strip_indent)
def x
@my_var ||= :foo
^^^^^^^ Memoized variable does not match method name.
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
end
Expand All @@ -19,7 +19,7 @@ def x
expect_offense(<<-RUBY.strip_indent)
def self.x
@my_var ||= :foo
^^^^^^^ Memoized variable does not match method name.
^^^^^^^ Memoized variable `@my_var` does not match method name `x`. Use `@x` instead.
end
RUBY
end
Expand All @@ -30,7 +30,7 @@ def self.x
expect_offense(<<-RUBY.strip_indent)
foo = def x
@y ||= :foo
^^ Memoized variable does not match method name.
^^ Memoized variable `@y` does not match method name `x`. Use `@x` instead.
end
RUBY
end
Expand All @@ -41,7 +41,7 @@ def self.x
expect_offense(<<-RUBY.strip_indent)
def x
@y ||= begin
^^ Memoized variable does not match method name.
^^ Memoized variable `@y` does not match method name `x`. Use `@x` instead.
:foo
end
end
Expand All @@ -55,7 +55,7 @@ def x
def foo
helper_variable = something_we_need_to_calculate_foo
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable does not match method name.
^^^^ Memoized variable `@bar` does not match method name `foo`. Use `@foo` instead.
end
RUBY
end
Expand Down

0 comments on commit 900ae13

Please sign in to comment.