ProGM
ProGM

Reputation: 7108

List all rails routes with http method associated

I use this method to list all routes of my rails application:

def routes
  Rails.application.routes.routes.collect do |r|
    { path: r.path.spec.to_s }
  end
end

My result is:

[
  { :path => '/my/path/' },
  { :path => '/my/path2/' },
  ...
]

I want to obtain also the http method used for that route. How to do it?
Exploring class documentation I couldn't find it.

The expected result is:

[
  { :path => '/my/path/', :method => :get },
  { :path => '/my/path2/', :method => :post },
  ...
]

There is a way to obtain the http method associated to a route? (or a list of methods)

Upvotes: 2

Views: 360

Answers (1)

sdabet
sdabet

Reputation: 18670

ActionDispatch::Journey::Route has a verb method which returns a RegExp:

You could try this:

def routes
    Rails.application.routes.routes.collect do |r|
        { path: r.path.spec.to_s, :verb => r.verb.source[/[a-z]+/i].to_sym }
    end
end

Upvotes: 3

Related Questions