class TheHelp::Service
An Abstract Service
Class with Authorization and Logging
Define subclasses of Service
to build out the service layer of your application.
@example
class CreateNewUserAccount < TheHelp::Service input :user input :send_welcome_message, default: true authorization_policy do call_service(Authorize, permission: :admin_users).success? end main do # do something to create the user account if send_welcome_message call_service(SendWelcomeMessage, user: user) do |result| callback(:message_sent) if result.success? end end result.success end callback(:message_sent) do |message| # do something really important with `message`, I'm sure end end class Authorize < TheHelp::Service input :permission authorization_policy allow_all: true main do if user_has_permission? result.success else result.error 'Permission Denied' end end end class SendWelcomeMessage < TheHelp::Service input :user main do message = 'Hello, world!' # do something with message... result.success message end end CreateNewUserAccount.(context: current_user, user: new_user_object)
@example Calling services with a block
# The service result will be yielded to the block if a block is present. class CanTakeABlock < TheHelp::Service authorization_policy allow_all: true main do result.success :the_service_result end end service_result = nil CanTakeABlock.call { |result| service_result = result.value } service_result #=> :the_service_result
@note See README section “Running Callbacks”
Constants
- CB_NOT_AUTHORIZED
The default :not_authorized callback
It will raise a TheHelp::NotAuthorizedError when the context is not authorized to perform the service.
Public Class Methods
attr_accessor(*names, make_private: false, private_reader: false, private_writer: false)
click to toggle source
Defines attr_accessors with scoping options
Calls superclass method
# File lib/the_help/service.rb, line 97 def attr_accessor(*names, make_private: false, private_reader: false, private_writer: false) super(*names) names.each do |name| private name if make_private || private_reader private "#{name}=" if make_private || private_writer end end
call(*args, &block)
click to toggle source
Convenience method to instantiate the service and immediately call it
Any arguments are passed to initialize
# File lib/the_help/service.rb, line 109 def call(*args, &block) new(*args).call(&block) end