简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM