In Rails 2, I used to use

    controller, action, nil)

to get a list of routes that matched a hash. With the advent of Rack-based routing in Rails 3, this approach went the way of the dodo.

I spent a bit of time nosing around in the source for the Rails 3-compatible way of doing this. Like a lot of other useful stuff you can find what you’re looking for under Rails.application, in this case Rails.application.routes, which gives us an ActionDispatch::Routing::RouteSet. This isn’t actually an enumerable or a Set as you’d expect. It has an Array property routes, however. Now if I want a list of routes that use a controller and an action, I can write

    def routes_for_controller_and_action(controller, action)
        routes = {|r| r.defaults[:controller] == controller && r.defaults[:action] == action}

This is really useful in a usage logging scenario, as we can put a report in front of admins to say which areas of the site are being used most and use a familiar-looking URL rather than the MVC implementation-specific “controller” and “action” nomenclature.

© 2014 ZephyrBlog Suffusion theme by Sayontan Sinha