How to find unused gems in my Gemfile

天大地大妈咪最大 提交于 2019-11-29 20:56:33

I doubt if there is an automated way to find unused gems in the Gemfile.

For someone who has built the application over time, it should be easy to manually identify gems that were discarded along the way for some reason or the other.

For a legacy application inherited from someone else, it is a much difficult task to manually identify unused gems. If there is comprehensive test coverage for the system, it would help in removing unused gems by trial and error, while ensuring that the tests pass at each change in the Gemfile.

Use linux' file access time to see what's actually being used.

This requires:

  1. project's gems isolated in an rvm gemset
  2. gems installed on a partition mounted with the atime (strictatime on ubuntu 12.04) option:

    sudo mount -o remount,strictatime /

  3. complete test coverage (i.e. we'll be relying on test runs to update file access times)

Note the time and run your tests. Then from your gemdir, do:

ls --time-style long-iso -ltud1 $PWD/*/lib/** | grep "21:44" | sed s/.*gems.// | sed s/.lib.*// | sort -u

Change the 21:44 to whatever time you ran the tests at.

Any gem should be considered for removal if all tests pass in its absence.

Assuming you have good test coverage - particularly high-level functional tests - you could write a script to selectively remove one gem at a time. ie run all your tests N times, where N is the number of gems in your Gemfile and each test has one missing gem. That will help weed out gems not pulling their weight.

You can use the gem_bench gem to analyze your Gemfile and identify which gems do not need to be required at boot time. From there it just requires a bit of analysis to determine which gems can be removed completely.

To generate a list of gems that can be removed from boot time:

  1. Add gem 'gem_bench', :group => :console to your Gemfile.
  2. Run bundle install
  3. Run bundle exec rails console with the following command:
  4. a = GemBench.check({verbose: true})
iltempo

There is the bundle clean --force command to remove gems outside the Gemfile.lock definitions.

See bundle-clean.

Run your tests and then:

gem stale

Which does the following:

The stale command lists the latest access time for all the files in your installed gems.

You can use this command to discover gems and gem versions you are no longer using.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!