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
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