Controller, Concern, Model, Service... Comment savoir où mettre son code ?


Vous-vous êtes surement déjà posé cette question; quel est le meilleur endroit pour mettre ce bout de code Ruby ? Dans une application Rails, il y a le choix et cette question peut être résolue en utilisant cette règle simple (qui n'est pas de moi) :

Does your code handle routing, params or do other controller-y things?

If so, don’t use a service object — your code belongs in the controller.

Are you trying to share your code in different controllers?

In this case, don’t use a service object — use a concern.

Is your code like a model that doesn’t need persistence?

If so, don’t use a service object. Use a non-ActiveRecord model instead.

Is your code a specific business action? (e.g., “Take out the trash,” “Generate a PDF using this text,” or “Calculate the customs duty using these complicated rules”)

In this case, use a service object. That code probably doesn’t logically fit in either your controller or your model.