FloatingRock
FloatingRock

Reputation: 7065

Rails: Separating ApplicationController from ApiController

My app/ folder looks like this

.
├── controllers
|   └── api
|       └── v1
|           ├── card_controller.rb
|           └── user_controller.rb
|   └── website
|       └── account_controller.rb
...

I'd like the controllers in the website folder to inherit from a WebsiteController and the controllers in the api folder to inherit from an ApiController. How can this be achieved? Specifically, what files need to be created, and what class definitions must be used?

Upvotes: 1

Views: 628

Answers (1)

Nicky McCurdy
Nicky McCurdy

Reputation: 19524

I recommend creating inheritable classes in controllers/website/website_controller.rb and controllers/api/v1/api_controller.rb.

You may use the following to easily inherit from these new controllers. This is similar to how the default generated Rails app has every controller inherit from ApplicationController.

Files

website_controller.rb

class WebsiteController < ApplicationController
end 

account_controller.rb

class AccountController < WebsiteController
end

Alternatives

  • It might be possible to metaprogram inheritance or includes for files in these directories, though I recommend against it to make your code more readable.
  • If your inheritable classes just solve one specific problem each, or have miscellaneous helper functions and not much else, you should probably use concerns or helpers respectively instead.
  • If you only need this level for inheritance for your API and the rest of your app, it might be best to extract your API into a separate application (which may or may not be a Rails app).

Upvotes: 1

Related Questions