From d95c9f459eb407e79f09950e4d4d01460938b38c Mon Sep 17 00:00:00 2001 From: Dhamo1107 Date: Thu, 22 Aug 2024 17:44:45 +0530 Subject: [PATCH] Handled methods used in callbacks, added ruby strings in strip_comments --- lib/un_used_methods/analyzer.rb | 21 ++++++++++++++++++--- 1 file changed, 18 insertions(+), 3 deletions(-) diff --git a/lib/un_used_methods/analyzer.rb b/lib/un_used_methods/analyzer.rb index 884478c..e82f7a2 100644 --- a/lib/un_used_methods/analyzer.rb +++ b/lib/un_used_methods/analyzer.rb @@ -54,6 +54,9 @@ def method_used?(method, definition_file) # Check if method is used in any file other than its own definition file return true if file_contains_method_call?(files, definition_file, method_call_patterns) + # Check if the method is used in callbacks like `before_action` or `after_action` + return true if method_used_in_callback?(method, files) + # Check method usage within its own file method_called_in_own_file?(definition_file, method_call_patterns) end @@ -61,7 +64,9 @@ def method_used?(method, definition_file) def build_method_call_patterns(method) [ /(\.|^|\s)#{method}\s*\(/, # Matches method calls with parameters - /(\.|^|\s)#{method}\b(?!\()/ # Matches method calls without parameters + /(\.|^|\s)#{method}\b(?!\()/, # Matches method calls without parameters + /(\.|^|\s):#{method}\b/, # Matches method references as symbols (e.g., :method_name) + /\b#{method}\b/ # Matches method as a standalone word, e.g., when passed as an argument ] end @@ -79,6 +84,16 @@ def method_called_in_own_file?(definition_file, patterns) patterns.any? { |pattern| content.scan(pattern).count > 1 } end + def method_used_in_callback?(method, files) + # Create a dynamic regex pattern to match any Rails callback with the given method + callback_pattern = /\b(before|after|around|validate|commit|save|create|update|destroy)\w*\s*:#{method}\b/ + + files.any? do |file| + content = read_file(file) + content.match?(callback_pattern) + end + end + def read_file(file) content = File.read(file) strip_comments(content, file) @@ -87,8 +102,8 @@ def read_file(file) def strip_comments(content, file) case File.extname(file) when ".rb" - # Remove Ruby comments - content.gsub(/#.*$/, "") + # Remove Ruby comments and strings + content.gsub(/#.*$/, "").gsub(/"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'/, "") when ".erb", ".html", ".haml", ".slim" # Remove HTML, ERB, HAML, SLIM comments content.gsub(//m, "").gsub(/<%#.*?%>/m, "")