Skip to content

Commit

Permalink
[Fix rubocop#5648] Suggest valid memoized instance variable for predi…
Browse files Browse the repository at this point in the history
…cate method
  • Loading branch information
Satyajit Phanse committed Mar 7, 2018
1 parent b65c4d5 commit b74748e
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### Bug fixes

* [#5648](https://github.com/bbatsov/rubocop/issues/5648): Suggest valid memoized instance variable for predicate method. ([@satyap][])

## 0.53.0 (2018-03-05)

### New features
Expand Down
3 changes: 2 additions & 1 deletion lib/rubocop/cop/naming/memoized_instance_variable_name.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ module Naming
#
class MemoizedInstanceVariableName < Cop
MSG = 'Memoized variable `%<var>s` does not match ' \
'method name `%<method>s`. Use `@%<method>s` instead.'.freeze
'method name `%<method>s`. Use `@%<suggested_var>s` instead.'.freeze

def self.node_pattern
memo_assign = '(or_asgn $(ivasgn _) _)'
Expand All @@ -55,6 +55,7 @@ def on_def(node)
msg = format(
MSG,
var: ivar_assign.children.first.to_s,
suggested_var: method_name.to_s.chomp('?'),
method: method_name
)
add_offense(node, location: ivar_assign.source_range, message: msg)
Expand Down
12 changes: 12 additions & 0 deletions spec/rubocop/cop/naming/memoized_instance_variable_name_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,18 @@ def foo
end
end

context 'memoized variable after other code does not match method name' do
it 'registers an offense' do
expect_offense(<<-RUBY.strip_indent)
def foo?
helper_variable = something_we_need_to_calculate_foo
@bar ||= calculate_expensive_thing(helper_variable)
^^^^ Memoized variable `@bar` does not match method name `foo?`. Use `@foo` instead.
end
RUBY
end
end

context 'memoized variable matches method name' do
it 'does not register an offense' do
expect_no_offenses(<<-RUBY.strip_indent)
Expand Down

0 comments on commit b74748e

Please sign in to comment.