Hexx::Services
The base class for domain service object
Synopsis
Every service object is responcible for providing a single business operation.
Its API consists of 4 public methods:
.newto instantiate the object.#inject_dependencyto inject a dependency from another object.#subscribeto subscribe external listener for receiving the object's notification (events).#callto execute the object.
Except for API, the base class provides a DSL for the service, that includes the following private methods:
.attributeto declare initializable attributes for the object..validateand.validatesto declare validations/policies for the object..depends_onto declare the injectable dependency of the object from another service object class.#attributeswith a hash of initialized attributes.#executeto do sequence operations, ending by invocation of#publish!, that throws:publishedexception to be catched by#call. If no exception was raised, the#callwill publish:successevent.#invalidto raise a validation error.#validateand#validate!to call declared validations when necessary.#remember,#publishand#publish!to create, collect, publish and return events.#translateto translate a text in the scope of the service object.
When defining a service you have to
- declare its attributes,
- declare validation rules,
- declare service dependencies,
- define the
#executemethod.
class AddItem < Hexx::Services::Base
attribute :uuid
attribute :name, writer: -> value { Name.new value }
validate { invalid :blank unless uuid }
validates :name
depends_on :get_item, GetItem
private
def execute
publish! :error unless validate.valid?
event = get_item.new(uuid: uuid).call
publish! :found if event.type == :found
item = Item.save! attributes
publish :added, "published", item: item
end
end
Installation
Add this line to your application's Gemfile:
# Gemfile
gem "hexx-services"
Then execute:
bundle
Or add it manually:
gem install hexx-services
Compatibility
Tested under rubies compatible to MRI 2.1+.
Uses RSpec 3.0+ for testing and hexx-suit for dev/test tools collection.
Contributing
- Read the STYLEGUIDE
- Fork the project
- Create your feature branch (
git checkout -b my-new-feature) - Add tests for it
- Commit your changes (
git commit -am '[UPDATE] Add some feature') - Push to the branch (
git push origin my-new-feature) - Create a new Pull Request
License
See the MIT LICENSE.