Skip to content

Commit 4fc5e2d

Browse files
dpostorivobbatsov
authored andcommitted
[Fix #4322] Fix Style/MultilineMemoization autocorrection
1 parent c769543 commit 4fc5e2d

File tree

3 files changed

+37
-2
lines changed

3 files changed

+37
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,7 @@
6565
* [#4646](https://github.com/bbatsov/rubocop/issues/4646): Make `Lint/Debugger` aware of `Kernel` and cbase. ([@pocke][])
6666
* [#4643](https://github.com/bbatsov/rubocop/issues/4643): Modify `Style/InverseMethods` to not register a separate offense for an inverse method nested inside of the block of an inverse method offense. ([@rrosenblum][])
6767
* [#4593](https://github.com/bbatsov/rubocop/issues/4593): Fix false positive in `Rails/SaveBang` when `save/update_attribute` is used with a `case` statement. ([@theRealNG][])
68+
* [#4322](https://github.com/bbatsov/rubocop/issues/4322): Fix Style/MultilineMemoization from autocorrecting to invalid ruby. ([@dpostorivo][])
6869

6970
### Changes
7071

lib/rubocop/cop/style/multiline_memoization.rb

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -54,8 +54,7 @@ def on_or_asgn(node)
5454
def autocorrect(node)
5555
lambda do |corrector|
5656
if style == :keyword
57-
corrector.replace(node.loc.begin, 'begin')
58-
corrector.replace(node.loc.end, 'end')
57+
keyword_autocorrect(node, corrector)
5958
else
6059
corrector.replace(node.loc.begin, '(')
6160
corrector.replace(node.loc.end, ')')
@@ -71,6 +70,29 @@ def bad_rhs?(rhs)
7170
rhs.kwbegin_type?
7271
end
7372
end
73+
74+
def keyword_autocorrect(node, corrector)
75+
node_buf = node.source_range.source_buffer
76+
corrector.replace(node.loc.begin, keyword_begin_str(node, node_buf))
77+
corrector.replace(node.loc.end, keyword_end_str(node, node_buf))
78+
end
79+
80+
def keyword_begin_str(node, node_buf)
81+
indent = config.for_cop('IndentationWidth')['Width'] || 2
82+
if node_buf.source[node.loc.begin.end_pos] == "\n"
83+
'begin'
84+
else
85+
"begin\n" + (' ' * (node.loc.column + indent))
86+
end
87+
end
88+
89+
def keyword_end_str(node, node_buf)
90+
if node_buf.source_line(node.loc.end.line) =~ /[^\s\)]/
91+
"\n" + (' ' * node.loc.column) + 'end'
92+
else
93+
'end'
94+
end
95+
end
7496
end
7597
end
7698
end

spec/rubocop/cop/style/multiline_memoization_spec.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -121,6 +121,18 @@
121121
baz
122122
end
123123
RUBY
124+
125+
it_behaves_like 'code with offense',
126+
<<-RUBY.strip_indent,
127+
foo ||= (bar ||
128+
baz)
129+
RUBY
130+
<<-RUBY.strip_indent
131+
foo ||= begin
132+
bar ||
133+
baz
134+
end
135+
RUBY
124136
end
125137
end
126138

0 commit comments

Comments
 (0)