Kir
Kir

Reputation: 8111

Rails routes match by regexp

I have routes rule:

match '*path' => redirect("/some_scope/%{path}")

But I need to apply this only if the current path doesn't start from /some_scope/

Upvotes: 2

Views: 2979

Answers (2)

Kir
Kir

Reputation: 8111

Here is my solution:

DEFAULT_PATH_SCOPE = "/my_scope"

default_scope_constraint = ->(request) do
  !request.path.starts_with?(DEFAULT_PATH_SCOPE)
end

constraints(default_scope_constraint) do
  match '*path' => redirect("#{DEFAULT_PATH_SCOPE}/%{path}")
end

Upvotes: 0

varatis
varatis

Reputation: 14740

http://guides.rubyonrails.org/routing.html#dynamic-segments

How do I use regular expressions in a Rails route to make a redirection?

Those two should be able to help you solve your problem. It would be nice if you gave us real code, so I can determine exactly what you're trying to do, because it seems like you might not even need a regex in this case.

If you're trying to do what I think you're trying to do... that is apply a scope to a path if it doesn't already contain that scope, you would be better off doing before_filters in your ApplicationController. That is:

before_filter :check_locale

protected

def check_locale
  redirect_to "/some_scope#{request.path_info}" if not request.path_info =~ /^\/some_scope\//
end

Upvotes: 1

Related Questions