Ruby on rails Rails.application.routes.recognize_路径与designe认证路由

Ruby on rails Rails.application.routes.recognize_路径与designe认证路由,ruby-on-rails,ruby-on-rails-3,devise,Ruby On Rails,Ruby On Rails 3,Devise,我有一个设计启用的路线,如下所示: #config/routes.rb authenticated :user { root :to => 'home#signed_in' } root :to => 'home#index 和控制器: #app/controllers/home_controller.rb class HomeController < ApplicationController def signed_in Rails.application.

我有一个设计启用的路线,如下所示:

#config/routes.rb
authenticated :user {
  root :to => 'home#signed_in'
}
root :to => 'home#index
和控制器:

#app/controllers/home_controller.rb
class HomeController < ApplicationController
  def signed_in
    Rails.application.routes.recognize_path '/'
  end
end
我需要这样的东西来根据
request.referer
controller name在销毁操作中呈现不同的模板。如何获取此类URL的“已验证”控制器/操作名称?

您可以使用以下方法:

  authenticated :user do
    root :to => 'home#signed_in'
  end

  unauthenticated :user do
    root :to => 'home#index'
  end
然后打电话给我

RouteRecognizer.is_route?('http://whatever')

似乎使用
Rails.application.routes.recognize_path
无法很好地处理自定义路由约束,如designe
#authenticated
方法

对于需要请求相关对象的约束(如Desive期望位于请求环境哈希中的warden实例),Recognite_path将无法正常工作。如果在控制器代码中执行此操作,则可以将warden对象从request.env传递到recognize_path调用,或者尝试将该对象传递到正在识别路径的类

另一方面,由于recognize_path不是一个有文档记录的公共API,我强烈建议您不要使用它,而是在应用程序上保存一些params散列,而不是原始URL


解决此问题的一个方法是在会话中保存控制器/操作名称,并在需要时访问它们。

使用:users而不是:users我确实希望获得“已验证”路由,因此添加“未验证”不会改变任何内容。
class RouteRecognizer
  include Singleton

  ROUTE_LIST = Rails.application.routes.routes.collect{|r| r.path.spec.to_s}
  REGEX_ROUT_LIST = ROUTE_LIST.map{|r|
    Regexp.new(r.gsub(/\:(.*)id/, "(\d+)").gsub("(.:format)", ""))
  }

  def self.is_route?(path)
    REGEX_ROUT_LIST.each do |regex|
      return true if !!(path =~ regex)
    end
    false
 end
end
RouteRecognizer.is_route?('http://whatever')