Spidy
Spidy

Reputation: 40002

Rails routes enforce controller inheritance

Is there a way to enforce that a controller inherits from another one in the route declaration? For example, if class B was a subclass of class A, allow it to use the route. Something like this?

match '/login/:controller', :constraint => { :inherits => A }

Update

As a more concrete example, I have an OAuthController that accepts logins from several sources. Let's say Google, Facebook, and Twitter. I have a GoogleController, FacebookController, and TwitterController that are all subclasses of OAuthController. So right now I accept the following routes:

/login/google
/login/facebook
/login/twitter

I might add or remove others at any time but I don't want to change my route. I also only want the :controller to be a subclass of :OAuthController. Is there a way to enforce that?

Upvotes: 1

Views: 716

Answers (1)

mliebelt
mliebelt

Reputation: 15525

I don't think that there is support out of the box for what you want to reach. However, there may be a way to go for. Have a look at "Rails Guides to Routing, Advanced Constraints". It uses a request object which is not exactly what you want to have, but may be sufficient.

The idea goes like that:

  • Implement a constraint with the necessary methods.
  • In the method matches?(request), do what you want to prove.
  • Integrate it by adding the route constraint:

    match "*path" => "login/:action",
      :constraints => LoginConstraint.new
    

This is the code for the implementation:

class BlacklistConstraint
  def initialize
    ... # necessary initialization here
  end

  def matches?(request)
    ... # Here is your check that returns true or false
  end
end

Upvotes: 1

Related Questions