A service pattern with a simple API.
result=ASolidService.call(any: 'thing',you: 'like')result.success?#=> trueresult.fail?#=> false- One service per action
- Service only has one public method
.callwith a hash input argument - The
.callalways return aStateobject. You can ask the state object the execution result
Check the Q&A for popular questions like:
- Is this gem has any different than interactor, simple_command and dry-monads?
- You use rescue to handle control flow? That's a bad idea.
Install the gem and add to the application's Gemfile by executing:
$ bundle add solidserviceOr manually add it in Gemfile
gem'solidservice'Here is an example for Rails app.
- Create a
servicesfolder
mkdir app/services- Create the service you want
classUpdateUser < SolidService::Basedefcallifuser.update(user_params)success!(user: user)elsefail!(user: user)endendprivatedefuser@user ||= User.find(params[:id])enddefuser_params@user_params ||= params[:user_params]endend- Use this service in controller
classUsersController < ApplicationControllerdefupdateresult=UpdateUser.call(id: params[:id],user_params: params.require(:user).permit(:email))ifresult.success?redirect_toroot_pathelse@user=result.userrender:editendendendsuccess!- Success the service immediately, any code after it won't be execute (Recommend)success- Just update the state to successfail!- Fail the service immediately, any code after it won't be execute (Recommend)fail- Just update the state to fail
You can send data with state object like this:
success!(user: user)success(user: user,item: item)fail!(email: email,error: error)fail(error: error)Then we can get those data on the result:
result=ExampleService.callresult.success?#=> trueresult.userresult.itemresult.success?#=> falseresult.errorresult.emailIf you don't call above 4 methods, the service will be marked as success by default. When some services which just want to execute some actions and don't want to return anything, go ahead, SolidService will take care of it.
classACommandService < SolidService::Basedefcall# Do some actions that don't need to return anythingendendresult=ACommandService.callresult.success?#=> trueSometimes, we want to use a service in another service, but don't want to doing if/else on the state object everywhere, then we can use call! for the inner service. Then the service will raise error on failure.
classAction2 < SolidService::Basedefcallfail!(error: StandardError.new('something wrong'))endendclassAction1 < SolidService::BasedefcallAction2.call!endendresult=Action1.callresult.fail?#=> trueresult.error#=> #<StandardError: something wrong>Here are some the key advantages:
- It's much simple then other service like pattern.
- You can master it in a few of seconds and start to use it in real projects.
- Easy to write concise, readable and maintainable code with only 4 DSL
- Unify input and output but without any restrictions
- The input is a hash called
params. It's Rails dev friendly, use it just like a controller - The output is an state object with hash data. Call any methods on it, it won't raise error on data missing.
- The input is a hash called
This gem doesn't force you to do that. Those rescue handle on Success and Failure only work when you use success! and fail!. You can only use success and fail if you don't like the rescue pattern.
I use it for a very practical reason. I believe many people have met this issue in the controller:
classExampleController < ApplicationControllerdefcreateifa_conditionrender:a_pageandreturnend# ......endendI meet the same issue in service:
classExampleService < SolidService::Basedefcallifcheck_1_failedfail(user: user)andreturnendifcheck_2_failedfail(user: user)andreturnend# ...endendI hate this. It's very low readability. So I comes up with with the rescue way to end the action immediately when I call success! and fail!
classExampleService < SolidService::Basedefcallfail!(user: user)ifcheck_1_failedfail!(user: user)ifcheck_2_failed# ...endendI think it's much better. So you see, the rescue is for success! and fail! only. You can still use success and fail. Even me, I did have a few circumstances need me to call success multiple times, then I will use it also.
bundle install
meval rake # Run test
meval -a rake # Run tests against all Ruby versions and Rails versionsBug reports and pull requests are welcome on GitHub at https://github.com/hoppergee/solidservice. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the code of conduct.
The gem is available as open source under the terms of the MIT License.
Everyone interacting in the SolidService project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the code of conduct.