I want to redirect to a different url when the route constraint fails
Route.rb
match '/u' => 'user#signin', :constraints => BlacklistDomain
blacklist_domain.rb
class BlacklistDomain
BANNED_DOMAINS = ['domain1.com', 'domain2.com']
def matches?(request)
if BANNED_DOMAINS.include?(request.host)
## I WANT TO REDIRECT HERE WHEN THE CONDITION FAILS
else
return true
end
end
end
In Rails, a RESTful route provides a mapping between HTTP verbs, controller actions, and (implicitly) CRUD operations in a database. A single entry in the routing file, such as. map.resources :photos. creates seven different routes in your application: HTTP verb.
Rails routes are matched in the order they are specified, so if you have a resources :photos above a get 'photos/poll' the show action's route for the resources line will be matched before the get line. To fix this, move the get line above the resources line so that it is matched first.
In a way, namespace is a shorthand for writing a scope with all three options being set to the same value.
Because Rails routes are executed sequentially, you can mimic conditional login in the following manner:
# config/routes.rb
match '/u' => 'controller#action', :constraints => BlacklistDomain.new
match '/u' => 'user#signin'
The first line checks whether the conditions of the constraint are met (i.e., if the request is emanating from a blacklisted domain). If the constraint is satisfied, the request is routed to controller#action
(replace accordingly, of course).
Should the conditions of the constraint fail to be met (i.e., the request is not blacklisted), the request will be routed to user#signing
.
Because this conditional logic is effectively handled in your routes, your constraints code can be simplified:
# blacklist_domain.rb
class BlacklistDomain
BANNED_DOMAINS = ['domain1.com', 'domain2.com']
def matches?(request)
if BANNED_DOMAINS.include?(request.host)
return true
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With