rubyrequirezeitwerk

Fix ruby project inconsistent files using zeitwerk


For a large (non-Rails) ruby project with thousands files not following naming convention for class, module and constants that uses a lot require and require_relative and potential circular dependency, is there a way to detect them so that corrective action could be apply and allow adopting the code loader?

I have found something for Rails project https://github.com/rails/rails/blob/main/railties/lib/rails/zeitwerk_checker.rb


Solution

  • The require and require_relative calls are not important in the sense that if you migrate, they would be removed.

    One way to approach this would be to eager load the project, iterate over ObjectSpace to print const_source_location of class and modules whose path lives in the project.

    Then, in a temporary script not yet driving the project, instantiate a Zeitwerk loader, set its root directory or directories, and then check loader.all_expected_cpaths. This method gives you the constant paths expected in the project with the given configuration, and it does not load the code. So you can run this even if the project is not managed by Zeitwerk.

    Those two sources of data can be compared and could give you one metric.

    To make both of them converge, you will generally move things around. You can do this while staying in your project. Just move the files, put one thing in one file, and revise the require and require_relative calls so that the project still works (assuming those are not public interface and you can change locations).

    When that is re-organized, you can either rename constants if needed, or use inflections to leave them as they are.