DEV Community

Skyler Fisher
Skyler Fisher

Posted on

A Rails controller I keep copying between side projects

I have a small Rails controller pattern that keeps surviving my rewrites.

It has three pieces:

A filter step. Params go in, a hash of only the allowed keys comes out. Not strong parameters in the action — a small method that returns either the filtered hash or an error.

A service call. The controller doesn't know how the thing is built. It passes the hash to Foo::Create and handles the result.

A response switch. One place that turns success into the right JSON or redirect, and failure into 422 with the errors. No rescuing in the action unless it's a real exception.

It's not clever. It's maybe 40 lines. But it means every new endpoint in a side project looks the same, and I can delete a feature without hunting for its logic.

The thing I'm still unsure about: where do you put authorization? Before the service, inside it, or both?

Top comments (0)