Last Updated: February 25, 2016
·
13.6K
· tadas_t

Find routes in Rails console

If you are working with Rails 3 or 4 applications, you might find this helpful.

Most of us know, how cool $rake routes is, but those of you who work with larger applications are probably annoyed with slow rails app loading times, which is needed for rake tasks. Put this code in your ~/.irbrc file for a lightweight, application-independent solution to view and filter routes:

if defined? Rails

  if Rails::VERSION::STRING >= "4"

    # returns an array of routes in Rails 4
    def formatted_routes
      r = Rails.application.routes.routes
      i = ActionDispatch::Routing::RoutesInspector.new(r)
      f = ActionDispatch::Routing::ConsoleFormatter.new
      i.format(f).split("\n")
    end

  else
    require 'rails/application/route_inspector'

    # returns an array of routes in Rails 3
    def formatted_routes
      inspector = Rails::Application::RouteInspector.new
      inspector.format(Rails.application.routes.routes)
    end

  end

  # filter and print out the routes
  def routes(filter = nil)
    Rails.application.reload_routes!
    formatted = formatted_routes
    if filter
      formatted.select!{ |r| r.match(filter) }
    end
    puts formatted
  end
end

Raw gist for easy copying

Usage:

> routes
=> prints all routes
> routes /GET.*user/i
=> prints routes matching a given regex
> routes "user"
=> matches strings as well

Alternative solutions: zeus, sextant

1 Response
Add your response

Also, Rails 4 merged sextant in.
Just visit dev-url/rails/info/routes to see the routes.

over 1 year ago ·