Service objects¶
A service object executes one action of your domain logic. Use it instead of a large block of code in a controller or model.
Structure¶
Inherit from EasyExtensions::BaseService. It includes EasyExtensions::Callable, which defines the class method .call(...): it builds the service with the given arguments and runs the instance method call.
Name the class as a plain command, such as CreateUser or RegisterAccount, without a Service suffix. Put the file in app/services/ of your plugin. Prefix the name or wrap it in a module named after your plugin (see Prefixes).
call returns true or false, or an object (or self) when the service creates or retrieves something.
Example¶
EasyExtensions::JWT::GenerateAuthToken (app/services/easy_extensions/jwt/generate_auth_token.rb) takes a user and returns a token:
module EasyExtensions
module JWT
class GenerateAuthToken < EasyExtensions::BaseService
# @param [User] user
def initialize(user: User.current)
super()
@user = user
end
def call
EasyExtensions::JWT.encode(payload)
end
private
attr_reader :user
def payload
{
user_id: user.id,
user_login: user.login,
}
end
end
end
end
Call it with its arguments: