Rails Sitemap

“When something is too hard, it means that you’re not cheating enough. it means that you’re doing it wrong“. Generating a Rails sitemap (hash of application controllers and actions) is as simple as placing and calling this method in your application:

1234567891011121314  def controllers_and_actions    require 'find'    site_map = {}    Find.find(RAILS_ROOT + '/app/controllers') do |file_name|        if /_controller.rb$/ =~ file_name          name = File.basename(file_name, ".rb")          site_map[name] = []          Object.const_get(name.classify).instance_methods(false).each do |act|            site_map[name] << act          end        end    end    site_map  end

As the name of your method states, it is only for getting controllers and their action methods. However, if you have an ERB file defined in the controller’s view directory that does not have a corresponding method in the controller class, this page will not be in the site_map hash returned by your method. So generating a site map based on the hash from this method will be incomplete.

It wouldn’t be too hard to fix, you’d just need to have another Find.find block on the RAILS_ROOT “/app/views’ directory (making sure to ignore the layout directory and any erb files that already correspond to entries in the hash).

I wrote a sitemap rails plugin that will generate a sitemap.xml from sitemap.rb whose format is very similar to routes.rb. The home page of the sitemap plugin is http://github.com/flyerhzm/sitemap/tree/master