8

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

Nick Vanderbilt
  • 36,724
  • 29
  • 83
  • 106

3 Answers3

7

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.

Johannes
  • 1,370
  • 16
  • 15
  • well, in some cases using another class to exclude a simple word seems overkill. in our case it helps the dev team to keep track of the routes we're excluding in the same file – macool Jul 03 '19 at 16:13
7
(?!.*?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.

Community
  • 1
  • 1
Christoph Petschnig
  • 4,047
  • 1
  • 37
  • 46
2

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
Shadoath
  • 720
  • 1
  • 15
  • 31