0

Using rails 4.2.1

I want to store my rails declared routes from config/routes.rb into a ruby hash that I can access or render somewhere.

The hash should be of the format

{
  name: 'path',
  # e.g.
  login: '/login',
  home: '/'
}

How do I do this in rails?

Note: I think you get the routes through Rails.application.routes and maybe the names from Rails.application.routes.routes.named_routes.keys, but what's next?

3
  • Why do you want to do this? Why to you want to achieve? There might be a better solution than a hash if you tell us more about your use case. Commented May 13, 2015 at 4:53
  • @spickermann I want to create a json object to use on the front end to look up url strings based on route names. Commented May 13, 2015 at 4:56
  • This is what I expected. There is a Gem for supports that. Please see my answer below. Commented May 13, 2015 at 5:50

3 Answers 3

1

This will give you a Hash where the keys are the route names and the values are the paths:

routes = Hash[Rails.application.routes.routes.map { |r| [r.name, r.path.spec.to_s] }]

routes will now look like:

{
  "entities" => "/entities(.:format)",
  "new_entity" => "/entities/new(.:format)",
  "edit_entity" => "/entities/:id/edit(.:format)",
  "entity" => "/entities/:id(.:format)"
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you really have to do this, you can:

ri = ActionDispatch::Routing::RoutesInspector.new([])
result = ri.send :collect_routes, Rails.application.routes.routes

The result will be an array of hashes which look like:

{:name=>"product", :verb=>"GET", :path=>"/products/:id(.:format)", :reqs=>"products#show", :regexp=>"^\\/products\\/([^\\/.?]+)(?:\\.([^\\/.?]+))?$"}

Comments

1

You may want to use the JS-Routes gem that generates a javascript file that defines all Rails named routes as javascript helpers.

Setup (just add it to the asset pipeline):

# add to your application.js
/*
= require js-routes
*/

Usage your javascript code like this:

Routes.users_path()                   // => "/users"
Routes.user_path(1)                   // => "/users/1"
Routes.user_path(1, {format: 'json'}) // => "/users/1.json"

Find the documentation here: https://github.com/railsware/js-routes#usage

1 Comment

+1 Going to have to pick another answer that answered the question more precisely, but this definitely helped me deal with my problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.