ruby-on-railsruby

Finding unused views/partials in Ruby on Rails


I'm currently working on a largish Ruby on Rails project. It's old enough and big enough that it's not clear if all views are actually in use.

Is there any script/plugin out there that can generate a list of unused view files?


Solution

  • I wrote a script to find unused partials/views. I assumed, though, that "unused" means that a view-file is present for which no controller-method is defined (any more). The script does not check whether the view is called because there is no link from the default-route to it. This would have been far more complex.

    Place the following script in the application's script folder:

    #!/usr/bin/env ruby
    require 'config/environment'
    (Dir['app/controllers/*.rb'] - ['app/controllers/application.rb']).each do |c|
      require c
      base = File.basename(c, '.rb')
      views = Hash.new
      Dir["app/views/#{base.split('_')[0]}/*"].each do |v|
        views.store(File.basename(v).split('.')[0], v)
      end
      unused_views = views.keys - Object.const_get(base.camelcase).public_instance_methods - ApplicationController.public_instance_methods
      puts "Unused views for #{base.camelcase}:" if unused_views.size > 0
      unused_views.each { |v| puts views[v] }
    end
    

    It is kinda hackish and unfinished, but it does the job - at least for me.

    Execute it like this (you only need to change the execute-bit the first time with chmod):

    chmod +x script/script_name
    ./script/script_name
    

    Enjoy!