grip-framework / grip

The microframework for writing powerful web applications.

Home Page:https://grip-framework.github.io/docs/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Route with override would cause instantiating new instance of controller for each request

cyangle opened this issue · comments

I might be wrong, but it seems like the route override Proc would instantiate a new controller instance for each request.

The instantiation happens in the override Proc:

\{{ resource }}.new.as(\{{resource}}).\{{kwargs[:as].id}}(context)

When there's no method override, it uses the controller instance saved in the route instance:

payload.handler.call(context)

Ideally, the override should also use the controller instance saved in the route instance.

This behavior could be observed with below example server:

require "../src/grip"

class IndexController < Grip::Controllers::Http
  def initialize
    puts "Initializing Index Controller"
  end

  def get(context : Context) : Context
    puts "info"
    context
      .put_status(200) # Assign the status code to 200 OK.
      .json({"id" => 1}) # Respond with JSON content.
      .halt # Close the connection.
  end

  def index(context : Context) : Context
    puts "echo"
    id =
      context
        .fetch_path_params
        .["id"]

    # An optional secondary argument gives a custom `Content-Type` header to the response.
    context
      .json(content: {"id" => id}, content_type: "application/json; charset=us-ascii")
  end
end

class Application < Grip::Application
  def routes
    get "/info", IndexController
    get "/echo/:id", IndexController, as: :index
  end
end

app = Application.new
app.run

The log shows below messages:

Initializing Index Controller
Initializing Index Controller
2022-02-02 07:58:42 UTC [info] listening at http://0.0.0.0:5000.
info
info
info
Initializing Index Controller
echo
Initializing Index Controller
echo
Initializing Index Controller
echo

I think we should avoid instantiating new instances of the controllers for each request.
@grkek