Dynelight
Dynelight

Reputation: 2162

Writing cookies on Rails besides the controller, possible?

I'm working on an application stack that has a rather particular architecture. The forms component is loaded on a view, and when the action is submitted, an async call using sidekiq is performed. This calls an endpoint that validates the form data, but none of this is returned back to the server and after this process is fired, there is a redirect to another page.

We want to add cookies to write the status of this call sidekiq did. This is not possible to do on the controller as the controller when it is rendering the destination page has no knowledge of this event that occurred. The possibility of writing this cookie on the async callback is tempting but this is not done on the controller (The controller loads a class that contains a module with this functionality)

Question: Is it possible to write cookies in places not in the controller, such as classes or models? I'm assuming no, but I figured it might be an interesting question.

Upvotes: 0

Views: 34

Answers (1)

katafrakt
katafrakt

Reputation: 2488

It's not possible. Writing a cookie is a part of HTTP response, so you need to be in the request-response cycle, i.e. in the controller.

What you could do (and I did that more than once) is to have some kind of record in the database, storing a status of a background job, and from the page you redirected to periodically poll some endpoint with AJAX (or establish a Websocket connection) to check if the job has finished and with what status. Then you'll be able to set the cookie.

Upvotes: 3

Related Questions