如何简化此路由编码,以减少行数?

时间:2019-03-31 20:31:48

标签: ruby-on-rails devise controller routes

我已经扩展了Devise控制器(请参见本文Extending Devise Registration Controller),现在我想编辑路线。

该路线可以正常使用,但看起来很笨重。有没有一种方法可以重构此代码以使其占用更少的行?

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

1 个答案:

答案 0 :(得分:1)

我还要补充一点,我个人认为,动态生成的路线可能比有时值得的麻烦更多。

我相信以下方法会起作用。您可以根据路径名数组构造散列,然后使用该散列来分配控制器。

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