Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 586
Nick Vanderbilt Avatar asked Oct 26 '10 20:10

Nick Vanderbilt


3 Answers

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.

like image 26
Johannes Avatar answered Sep 25 '22 00:09

Johannes


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
like image 42
Shadoath Avatar answered Sep 23 '22 00:09

Shadoath


(?!.*?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.

like image 56
Christoph Petschnig Avatar answered Sep 27 '22 00:09

Christoph Petschnig