Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirecting from routes when the constraints fail

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
like image 423
Ross Avatar asked Oct 28 '13 13:10

Ross


People also ask

What are RESTful routes in Rails?

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.

What is match in Rails routes?

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.

What is namespace in Rails routes?

In a way, namespace is a shorthand for writing a scope with all three options being set to the same value.


1 Answers

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
like image 53
zeantsoi Avatar answered Nov 09 '22 07:11

zeantsoi