Skip to content

Getting started with Servactory

Conventions

  • Services inherit from Servactory::Base and reside in app/services. Common practice: create ApplicationService::Base as the base class for your services.
  • Group services by domain using namespaces, and name each class as a verb describing its action. Example: Users::Create, Orders::Process. Avoid adding Service to the namespace — the app/services directory already provides that context.

Version support

Ruby/Rails8.18.07.27.17.06.16.05.25.15.0
4.0
3.4
3.3
3.2
3.1

Installation

Add this to Gemfile:

ruby
gem "servactory"

And execute:

shell
bundle install

Preparation

First, prepare the base class for inheritance.

Automatically Since 2.5.0

Run the generator:

shell
bundle exec rails g servactory:install

This creates all necessary files.

See Rails Generators for all available options and generators.

Manually

ApplicationService::Exceptions

ruby
module ApplicationService
  module Exceptions
    class Input < Servactory::Exceptions::Input; end
    class Output < Servactory::Exceptions::Output; end
    class Internal < Servactory::Exceptions::Internal; end

    class Failure < Servactory::Exceptions::Failure; end
  end
end

ApplicationService::Result Since 2.5.0

ruby
module ApplicationService
  class Result < Servactory::Result; end
end

ApplicationService::Base

ruby
module ApplicationService
  class Base < Servactory::Base
    configuration do
      input_exception_class ApplicationService::Exceptions::Input
      internal_exception_class ApplicationService::Exceptions::Internal
      output_exception_class ApplicationService::Exceptions::Output

      failure_class ApplicationService::Exceptions::Failure

      result_class ApplicationService::Result
    end
  end
end

First service

Create your first service:

shell
bundle exec rails g servactory:service users/create first_name middle_name last_name

Generate a spec file:

shell
bundle exec rails g servactory:rspec users/create first_name middle_name last_name