Clamoris
Clamoris

Reputation: 447

Is there any way to get list of all rails resources?

I'd like to get all resources in project to log some actions on them. Is there any way to do this?

More specific, I'd like to get a hash of all resources and associated models, so i don't think rake output (and parsing it) isn't a suitable solution for this.

Upvotes: 2

Views: 2192

Answers (3)

Bruno Enten
Bruno Enten

Reputation: 1

I actually made a gem for that. It extendends Action Dispatch RouteSet an Mapper to populate an array of resources with a special option.

You can find it here: https://rubygems.org/gems/resources_nav

Upvotes: 0

Yan Foto
Yan Foto

Reputation: 11378

UPDATE: If you think I'm crazy

as I mentioned in the comments:

if you take a look at the mapper you would see that the keyword resource would expand to a number of gets, posts, etc. So I would say that your best chance is go through the paths and remember that the first part of the path is either a namespace or a resource name. Howerver, it would get really complicated for nested resources.

So I came up with a crazy idea: parsing the routes.rb file. You could read the routes.rb line by line and use a regex like resource(s*) :(\w*) to fine resources:

regex = %r(resource(s*) :(\w*))
resources = []
routes = File.open(File.join(Rails.root, "/config/routes.rb")).read
routes.each_line do |l|
  matches = regex.match l
  if matches && matches[1]
    resources << matches[1]
  end
end

This is however a very inflexible solution.

If you want it in your browser

Follow the guides:

To get a complete list of the available routes in your application, visit http://localhost:3000/rails/info/routes in your browser while your server is running in the development environment.

If you want to show in the terminal

bundle exec rake routes

if you want to filter it out:

bundle exec rake routes | grep 'my_namespace'

where name_space is any keyword you'd like!

If you want to do it programmatically:

Rails.application.routes.routes

For example this is the method I use to find routes with a given prefix:

def routes_starting_with(prefix)
    result = []

    Rails.application.routes.routes.each do |route|
      path = route.path.spec.to_s
      result << route if path.starts_with?("/#{prefix}")
    end

    result
  end
end

Upvotes: 4

Arup Rakshit
Arup Rakshit

Reputation: 118271

5.1 Listing Existing Routes

To get a complete list of the available routes in your application, visit http://localhost:3000/rails/info/routes in your browser while your server is running in the development environment. You can also execute the rake routes command in your terminal to produce the same output.

You may restrict the listing to the routes that map to a particular controller setting the CONTROLLER environment variable:

CONTROLLER=users bin/rake routes

Upvotes: 2

Related Questions