Controllers

A controller is called by the router which determines which controller to use for an HTTP request. Its goal will be to handle the request, and returning the appropriate output to the views (in our context, the views are JSON payload served to our frontend framework).

In Ruby on Rails, a controller class inherits from the base class ApplicationController.

By convention, controllers are named after their plural related entity followed by controller. For example, if we have a User entity, its controller would be named UsersController (users_controller.rb for the filename).

In our framework, we decided that controller should not contain any logic at all. Instead, they will delegate the logic to custom classes (services, commands, models, jobs...) using custom params. We will talk about those custom classes in the next sections.

Knowing that, here are the roles of our controller classes:

  • Intercept an HTTP request (via the router)

  • Format the HTTP params (using a params class)

  • Call the right processor (it can be a command, a service, a job or directly a model)

  • Return the output to the frontend using a dedicated serializer

Processing

A controller can either call a command, a service, or directly a model. In the commands section, you can find an example showing how a controller uses a command.

However, if there is no logic involved, a controller can bypass the need of using a command or a service, and can directly call a model class:

class UsersController < ApplicationController
  def index
    users = User.all

    render json: Api::Private::UserSerializer.new(users)
  end
end

In this example, we just need the list of all our users so we can directly call the User model to fetch them all. The only issue here is that we rarely want to just do that, but that's why we have other classes.

Last updated