Sobes.tech
Middle

At what point is the controller object created and what is its lifetime?

sobes.tech AI

Answer from AI

The controller object is created at the moment of receiving an HTTP request by the Rails router, which determines which controller and action should handle the request.

The lifetime of the controller object is limited to a single HTTP request. After processing the request and generating a response, Rails destroys the controller object.

This occurs in the following order:

  1. Request reception: The web server passes the HTTP request to the Rails application.
  2. Routing: Rails router analyzes the request and finds the corresponding controller and action.
  3. Controller initialization: Rails creates a new instance of the controller class defined by the router.
  4. Action execution: Rails calls the appropriate action method on the created controller object.
  5. Request processing: The action method performs logic, interacting with models and possibly other services.
  6. View rendering: The controller prepares data for the view and calls its rendering.
  7. Response sending: Rails forms an HTTP response, including the rendering result (or JSON, or another format), and sends it to the client.
  8. Controller destruction: After sending the response, the controller object and related variables (e.g., @instance_variables) are destroyed by Ruby's garbage collector.
# Approximate, as it looks at the framework level
# (not actual framework code, but a conceptual example)

class Rails::Application
  def receive_request(request)
    # request - HTTP request object
    route = Rails.application.routes.recognize(request)
    # route contains information about controller and action

    controller_class = route.controller_class
    action_name = route.action_name

    # Creating a controller instance
    controller_instance = controller_class.new
    controller_instance.request = request

    # Executing the action
    response = controller_instance.process(action_name)

    # Sending response and destroying the object
    send_response(response)
    # The controller_instance object becomes a candidate for garbage collection
  end
end

Thus, each new HTTP request leads to the creation of a new, independent controller instance. This guarantees that the state of one request does not affect the state of other requests. Instance variables (@) in the controller live exactly as long as one specific request is being processed.