Skip to content

Commit

Permalink
Handled methods used in callbacks, added ruby strings in strip_comments
Browse files Browse the repository at this point in the history
  • Loading branch information
Dhamo1107 committed Aug 22, 2024
1 parent 833e04b commit d95c9f4
Showing 1 changed file with 18 additions and 3 deletions.
21 changes: 18 additions & 3 deletions lib/un_used_methods/analyzer.rb
Original file line number Diff line number Diff line change
Expand Up @@ -54,14 +54,19 @@ 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

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

Expand All @@ -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)
Expand All @@ -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, "")
Expand Down

0 comments on commit d95c9f4

Please sign in to comment.