Skip to content

Commit a866a5b

Browse files
refactor: refactor regex
Moved them into methods to make it easier to understand and easier to move to another file in a future refactor
1 parent 5f97626 commit a866a5b

1 file changed

Lines changed: 37 additions & 3 deletions

File tree

lib/error_highlight/base.rb

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -349,7 +349,7 @@ def spot_call_for_name
349349
nd_recv, mid, nd_args = @node.children
350350
lineno = nd_recv.last_lineno
351351
lines = @fetch[lineno, @node.last_lineno]
352-
if mid == :[] && lines.match(/\G[\s)]*(\[(?:\s*\])?)/, nd_recv.last_column)
352+
if match_bracket_call(lines, mid, nd_recv.last_column)
353353
@beg_column = $~.begin(1)
354354
@snippet = lines[/.*\n/]
355355
@beg_lineno = @end_lineno = lineno
@@ -362,7 +362,7 @@ def spot_call_for_name
362362
@end_column = $~.end(0)
363363
end
364364
end
365-
elsif lines.match(/\G[\s)]*?(\&?\.)(\s*?)(#{ Regexp.quote(mid) }).*\n/, nd_recv.last_column)
365+
elsif match_method_call(lines, mid, nd_recv.last_column)
366366
lines = $` + $&
367367
@beg_column = $~.begin($2.include?("\n") ? 3 : 1)
368368
@end_column = $~.end(3)
@@ -375,14 +375,48 @@ def spot_call_for_name
375375
@snippet = lines
376376
@beg_lineno = @end_lineno = lineno
377377
end
378-
elsif mid.to_s =~ /\A\W+\z/ && lines.match(/\G\s*(#{ Regexp.quote(mid) })=.*\n/, nd_recv.last_column)
378+
elsif match_operator_call(lines, mid, nd_recv.last_column)
379379
@snippet = $` + $&
380380
@beg_lineno = @end_lineno = lineno
381381
@beg_column = $~.begin(1)
382382
@end_column = $~.end(1)
383383
end
384384
end
385385

386+
def match_bracket_call(lines, method_name, start_column)
387+
return nil unless method_name == :[]
388+
389+
pattern = /
390+
\G[\s)]* # Optional spaces or closing parens
391+
(\[(?:\s*\])?) # The '[' with optional whitespace and closing ']'
392+
/x
393+
394+
lines.match(pattern, start_column)
395+
end
396+
397+
def match_method_call(lines, method_name, start_column)
398+
pattern = /
399+
\G[\s)]*? # Optional spaces or closing parens
400+
(\&?\.) # '.' or '&.' operator
401+
(\s*?) # Optional spaces after the dot
402+
(#{Regexp.quote(method_name)}) # The method name itself
403+
.*\n # Rest of the line
404+
/x
405+
lines.match(pattern, start_column)
406+
end
407+
408+
def match_operator_call(lines, operator_name, start_column)
409+
return nil unless operator_name.to_s =~ /\A\W+\z/
410+
411+
pattern = /
412+
\G\s* # Optional leading spaces
413+
(#{Regexp.quote(operator_name)}) # The operator symbol
414+
=.*\n # Followed by '=' and rest of line
415+
/x
416+
417+
lines.match(pattern, start_column)
418+
end
419+
386420
# Example:
387421
# x.foo(42)
388422
# ^^

0 commit comments

Comments
 (0)