A simple rails plugin to create Service Objects
How to use my plugin.
Add this line to your application's Gemfile:
gem 'action_service'
And then execute:
$ bundle
Or install it yourself as:
$ gem install action_service
class UserRegistration < ActionService::Base
attr_accessor :name, :email, :password
actions :create_user, :send_welcome_email
def create_user
failure errors: user.errors unless user.save
end
def send_welcome_email
UserRegistrationMailer.welcome(to: email).deliver_later
success user: user
end
def user
@user ||= User.new(attribtues)
end
end
-
Create a class that inherits from ActionService::Base
-
Define attr_accessors. They will be the parameters that the service will receive
- You can use attributes to access all attr_accessors as a hash
-
Define actions that the service will execute as a list of symbols. This actions are the methods name on service
-
Create methods
-
When a failure occours, calls a failure method passing a hash as argument
-
For success, calls a success method passing a hash as argument as well
class UsersController < ApplicationController
def create
result = UserRegistration.call(**user_params)
if result.success?
render json: result.user, status: :created
else
render json: result.errors, status: :bad_request
end
end
private
def user_params
params.require(:user).permit(:name, :email, :password)
end
end
-
Use the call class method to execute and pass parameters
-
You can use the hash argument passed for the failure and success methods for getting information about your service
- The keys of hash become instance variables with your values
On service
failure errors: user.errors
Or
failure user_errors: user.errors
Getting the result
result.errors
Or
result.user_errors
The same happend to hash informed on success method
Contribution directions go here.
The gem is available as open source under the terms of the MIT License.