An implementation of the command pattern for Ruby
-
Context validation
-
Callbacks
Context:
- before_validation
- after_validation
Services:
- before_perform
- around_perform
- after_perform
-
Transations By default transactions are disabled, but you can include the following in your ApplicationService
transactional true
In case transactions are enabled after_commit will triger after after_peform
-
Asynchronous execution Instead of calling perform you can use perform_later to execute a service asynchronously, this uses ActiveJob.
Add this line to your application's Gemfile:
gem 'servitium'And then execute:
$ bundle install
Or install it yourself as:
$ gem install servitium
You define a context for the service, which describes what goes in and out
class ExampleContext < ApplicationContext
attribute :some, type: String, default: "new"
validates :some, presence: true
endYou can be very explicit in what goes in our out:
class ExampleContext < ApplicationContext
input do
attribute :some, type: String, default: "new"
validates :some, presence: true
end
output do
attribute :some, type: String, default: "new"
end
endAnd you define the service itself:
class ExampleService < ApplicationService
def perform
context.some.reverse!
end
endYou can also include the context in the service, for less complicated services:
class ExampleService < ApplicationService
context do
attribute :some, type: :string, default: "new"
end
def perform
context.some.reverse!
end
endNext you use it as follows:
ExampleService.perform(some: 'test').some # => tsetA service always returns it context
Services can also run in the background:
ExampleService.perform_later(some: 'test') # => #<ExampleContext>You can use the generator to generate service code:
❯ rails g servitium:service Example
create app/services/example_service.rb
create app/services/example_context.rb
create test/services/example_service_test.rb
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the Servitium project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.