DEV Community

Discussion on: Business logic in Rails with operators

 
alg profile image
Aleksey Gureiev • Edited

Good discussion. I replied to your comment without making any assumptions, so there's nothing personal. Made a specific effort not to rely anything said to anyone. And I never suggested to you specifically to read these sources, but to anyone willing to improve their coding-fu. I'm glad we share the library ticket. Now back to the subject.

As for database records sending emails, where did you get that? I was referring to the models. They don't do that. It's not their responsibility (SRP principle). In my systems, their responsibility lies in working with own data. You can hardly call Rails ActiveRecords and ActiveModels anemic as they provide a ton of functionality on top of plain DTOs.

The term "business logic" is so broad that we must be specific about what we call it. When I disagree with placing it into the models I mainly think about business operations. We got used to putting these into app/actions (named by controller "actions", the meat of which was extracted into their own classes). We also have app/services for general-purpose single-responsibility services for low-level operations.

Controllers in our apps look mostly like:

class ChatsController < ...
  def create
    authorize! Chat, to: :create?

    input = convert_input.(Chats::CreateInput, params)
    chat = create_chat.(input, user: current_user)

    respond_with chat
  end
end
Enter fullscreen mode Exit fullscreen mode

Here we shift non-HTTP stuff out of controller into business operations layer where Chats::CreateChatAction belongs. The added benefit of all this is if you ever thought of cutting your monolithic app into now-modern microservices, you already have your code nicely separated into contexts, but that is a different story.

Hope I made my point clear. Just to reiterate, there's no such thing as ideal and true architecture. We attempt to make our systems as manageable, extensible and decoupled as we can. Moving out business operations into a separate layer helps us a lot.