Richard Jarram
Richard Jarram

Reputation: 1004

How do I Simplify This Route Coding So It Takes Less lines?

I've extended my Devise controller (see this article Extending Devise Registration Controller) and now I want to edit my routes.

The route works fine as it is but it looks bulky. Is there a way to refactor this code to make it take less lines?

Rails.application.routes.draw do
  devise_for :users, controllers: {
      sessions: "sessions/sessions",
      registrations: "sessions/registrations",
      password: "sessions/passwords",
      confirmations: "sessions/confirmations",
      omniauth: "sessions/omniauth",
      unlocks: "sessions/unlocks",
   }
end

Upvotes: 0

Views: 69

Answers (1)

Jonathan Thom
Jonathan Thom

Reputation: 76

I'll add the caveat that in my personal opinion, dynamically generated routes can be more trouble than they're worth sometimes.

I believe the following will work though. You can construct a hash out of an array of path names, and then use that to assign your controllers.

  paths = ["sessions", "registrations", etc..]
  routes = paths.each_with_object({}) { |path, h| h[path] = "sessions/#{path}" }
  devise_for :users, controllers: routes

Upvotes: 1

Related Questions