我正在尝试在 Rails 3 中编写一条包罗万象的路线,但我想在其中保留一些术语。我特别遵循 David Burrows 的回答中这篇文章中提出的示例: 动态路线在 Rails 3 中,
我使用的语法如下:
match '*path' => 'router#routing', :constraints => lambda{|req| (req.env["REQUEST_PATH"] =~ /(users|my-stuff)/).nil? }
现在,该语法工作得很好 - 如果用户访问路径中包含“user”或“my-stuff”的页面,它就会陷入困境 -全部并转到具体的地方。如果用户访问任何其他 URL,它将进入我的路由逻辑。
我的问题更多的是关于可读性 - 有没有办法可以将路由与正则表达式之外的其他内容进行匹配?有没有办法提供一系列要匹配的术语?另外,有没有办法匹配路线的特定部分,而不是整个路线?
显然,Rails 具有内置路由,但该项目要求对于某些路由,控制器不能出现在 URL 中。因此,包罗万象。
感谢您的帮助
这是根据以下答案更新的路线文件:
class RouteConstraint
RESERVED_ROUTES = ['users', 'my-stuff']
def matches?(request)
!RESERVED_ROUTES.map {|r| request.path.include?(r)}.empty?
end
end
App::Application.routes.draw do
resources :categories
resources :sites
match '*path' => 'router#routing', :constraints => RouteConstraint.new
devise_for :users, :path_names =>{ :sign_in => 'login', :sign_out => 'logout', :registration => 'register' }
root :to => "router#routing"
end
I'm trying to write a catch-all route in Rails 3, but I want to reserve some terms in it. I'm specifically following the example put forth in this post, in the answer by David Burrows: Dynamic routes with Rails 3
The syntax I am using is the following:
match '*path' => 'router#routing', :constraints => lambda{|req| (req.env["REQUEST_PATH"] =~ /(users|my-stuff)/).nil? }
Now, that syntax works just fine - if a user visits a page with "user" or "my-stuff" in the path, it falls through the catch-all and goes to a specific place. If the user goes to any other URL, it goes to my routing logic.
My question is more about readability - is there a way I can match the route against something other than a regex? Is there a way to provide an array of terms to match against? Also, is there a way to match specific segments of the route, as opposed to the entire thing?
Obviously Rails has built-in routing, but this project has a requirement that for certain routes, the controller not be present in the URL. Hence, the catch-all.
Thanks for any help
Here's the updated routes file per the answer below:
class RouteConstraint
RESERVED_ROUTES = ['users', 'my-stuff']
def matches?(request)
!RESERVED_ROUTES.map {|r| request.path.include?(r)}.empty?
end
end
App::Application.routes.draw do
resources :categories
resources :sites
match '*path' => 'router#routing', :constraints => RouteConstraint.new
devise_for :users, :path_names =>{ :sign_in => 'login', :sign_out => 'logout', :registration => 'register' }
root :to => "router#routing"
end
发布评论
评论(2)
一旦您有多个路线可供尝试,如果您想要更清晰的内容,您可以使用类来指定约束:
此示例改编自 Rails 路由指南。
You can use a class to specify the constraints if you want something cleaner once you have multiple routes to try:
This example is adapted from the rails routing guide.
它需要一个 lambda;您可以使用任何您想要的标准。
It's taking a lambda; you can use whatever criteria you want.