Detect a pattern of two consequtive lines, anywhere. #11937
-
I have a cop that aims to detect 2 consecutive (ignoring whitespace) lines that have this pattern: def foo
@foo = T.let(@foo, T.nilable(Foo))
@foo ||= Foo.new
end The current implementation works, but it only works if these two lines are the first thing in the method body. E.g. this won't be caught: def foo
some
other
code
@foo = T.let(@foo, T.nilable(Foo))
@foo ||= Foo.new
end What would be the right way to match these two lines, and replace them without effecting other lines before/after them? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 5 replies
-
I briefly looked at your PR. You're looking for a You can use capturing within your pattern to return the exact child nodes within the |
Beta Was this translation helpful? Give feedback.
I briefly looked at your PR. You're looking for a
begin
node, which is going to capture the entire body of the method in your example. As you discussed in the PR, you would need use...
to make the matcher match when there is extra code (likely before and after the nodes you're looking for), but this will still be matching the entirebegin
node.You can use capturing within your pattern to return the exact child nodes within the
begin
that you are concerned about, and pass those into your correction rather than the parentbegin
node.