Skip to content

Instantly share code, notes, and snippets.

@jaydorsey
Created July 20, 2022 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jaydorsey/ad101a94effd7406c26c3f42ab85569e to your computer and use it in GitHub Desktop.
Save jaydorsey/ad101a94effd7406c26c3f42ab85569e to your computer and use it in GitHub Desktop.
Finding unused code in ruby and ruby on rails projects

This is a strategy I use to find unused code in ruby projects. These instructions are for macOS, but you only need access to the tools for this to work.

  1. Install unused following the instructions here
  2. Install universal-ctags. I use the brew instructions here
  3. Generate your tag file from your project root, including your library methods as well. I typically run /usr/local/bin/ctags . $(bundle list --paths) to add all of my library methods for the project. This has some other benefits, like allowing code-jumping in vim

    Bonus: You can set this command up as a git hook to run every time you make changes to your code locally. I have an example of this here

  4. Once this command is done, you can look at the tags file in your repository root to make sure it's populated with data correctly (cat tags | wc -l). For context, on an older project I have ~150,000 lines, on a newer project I have ~115,000 lines. In both cases, I have a healthy number of libraries included which are the bulk of the lines
  5. Generate your list of unused methods, classes, and constants with unused --ignore <path to gems/library> > out.txt

    In my case, all of my gems are in /Users/jay/.asdf/installs/*; we ignore these paths because I don't care if gem X has an extra method

Inspect the out.txt file to identify methods, classes, and constants you might be able to remove.

Caveats:

  1. This won't catch metaprogrammed or dynamically defined values, so be careful
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment