Private Detective addresses a common issue in Ruby projects where determining the appropriate visibility for class methods is sometimes overlooked. It is not always clear whether a method should be private, protected or public. Private Detective analyzes Ruby source code files and checks method visibility from inside and outside of the class.
Gemfile:
gem 'private_detective'
$ bundle install
Run the following in the project's route folder to begin scanning the project's files
$ private_detective
I'm always looking for a good excuse to look at the inner workings of external libraries such as Rubocop. I decided to create a simple gem of my own exploring the Ruby file parser and experiment with traversing the AST and it's nodes.
In real-world scenarios, it is common for public methods to inadvertently expose internal details, or for private methods to be unnecessarily restrictive. Private Detective was developed to streamline the identification and rectification of such visibility issues, offering a clearer understanding of method visibility within Ruby projects.
The gem employs the following process to analyze method visibility in your Ruby project:
-
Iteration Over Project Files:
- The gem iterates over your project files (currently the default is app/models only), inspecting the Ruby source code.
-
Parsing to AST Nodes:
- Each file is parsed into an Abstract Syntax Tree (AST) node using the
parser
gem.
- Each file is parsed into an Abstract Syntax Tree (AST) node using the
-
Traversing the AST:
- The gem traverses the AST nodes to identify class methods and their visibility modifiers: Private, Protected and the default Public.
-
Visibility Analysis:
- Based on the identified methods and modifiers, Private Detective provides insights into potential issues related to method visibility.
Private Detective found the following Class method information in your project:
Class: Client
Method: test_method_rubocop_client, visibility: public
Method contents:
models/user.rb:10:4 User#test_method_rubocop private [Correctable]
models/user.rb:11:4 User#test_private_method_rubocop protected [Correctable]
Method: test_additional_method_example, visibility: private
Method: test_additional_method_example_2, visibility: private
Class: Prompt
Method: message_content, visibility: public
Class: User
Method: test_method_rubocop, visibility: private
Method: test_private_method_rubocop, visibility: protected
End of report
Bug reports and pull requests are welcome on GitHub at https://github.com/rossme/private_detective.
The gem is available as open source under the terms of the MIT License.