ruby-on-railsnamespacesservice-object

rails namespacing service objects


I just wrote a service object between the controller and the model to "mark an attendance", so now I have one object for a controller action as follows:

class BookingAttendancesController
  def mark_attending
    attendance_marker = BookingAttendances::AttendanceMarkerService.new params, current_entity
    result = attendance_marker.call
    # flash msg etc
  end
end

And the service object (current implementation):

# app/services/booking_attendances/attendance_marker_service.rb
module BookingAttendances
  class AttendanceMarkerService
    def initialize(params, entity)
      # ...
    end
    def call
      # ...
    end
    # ...
  end
end

Ideally I would like to namespace the service object inside the controller class but rails expect that file to define the service class and not the service class nested in the controller.

The name for the module is available but I'm not sure if there's a convention for this. Overall I guess what bothers me the most is that I really would like to define that class inside the controller, but in a separate file (with that nesting probably). I could include the module in the controller, but that's not really my point. Is there a best practice for namespacing service objects in rails?


Solution

  • Your business logic is executed in controllers but if you extract it in services, the abstraction should be real.

    What I mean here is you only work with your models in the service. This way:

    A reusable service has then no reason to be namespaced after the name of the controller, it makes much more sense to be namespaced after the name of the model. So what you did is fine.

    BTW, even if it's kind of boring and ugly in the folders, I do put my services in app/services/services, this way I can namespace all services in a Services module.