开发者

Add constraint to route to exclude certain keyword

I am using Rails and I want to use contraint in route to exclude that route if keyword "incident" is anywhere in the url.

I am using rails3.

Here is my existing routes.

match ':arg', :to => "devices#show", :constraints => {:arg =开发者_运维问答> /???/} 

I need to put something in constraints so that it does not match if word "incident" is there.

Thanks


(?!.*?incident).*

might be what you want.

This is basically the same question as How to negate specific word in regex?. Go there for a more detailed answer.


Instead of bending regular expressions a way it is not intended to, I suggest this approach instead:

class RouteConstraint
  def matches?(request)
    not request.params[:arg].include?('incident')
  end
end

Foo::Application.routes.draw do
  match ':arg', :to => "devices#show", :constraints => RouteConstraint.new
  ...

Its a lot more verbose, but in the end more elegant I think.


Adding onto @Johannes answer for rails 4.2.5:

config/routes.rb (at the VERY end)

constraints(RouteConstraint) do
  get "*anythingelse", to: "rewrites#page_rewrite_lookup"
end

config/initializers/route_constraint.rb

class RouteConstraint
  def self.matches?(request)
    not ["???", "Other", "Engine", "routes"].any? do |check|
      request.env["REQUEST_PATH"].include?(check)
    end
  end
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜