lib/the_help/service.rb in the_help-1.4.2 vs lib/the_help/service.rb in the_help-1.5.0
- old
+ new
@@ -27,12 +27,12 @@
# call_service(SendWelcomeMessage, user: user,
# success: callback(:message_sent))
# end
# end
#
- # callback(:message_sent) do
- # # do something really important, I'm sure
+ # callback(:message_sent) do |message|
+ # # do something really important with `message`, I'm sure
# end
# end
#
# class Authorize < TheHelp::Service
# input :permission
@@ -47,15 +47,16 @@
# end
# end
#
# class SendWelcomeMessage < TheHelp::Service
# input :user
- # input :success, default: ->() { }
+ # input :success, default: ->(message) { }
#
# main do
- # # whatever
- # success.call
+ # message = 'Hello, world!'
+ # # do something with message...
+ # run_callback(success, message)
# end
# end
#
# CreateNewUserAccount.(context: current_user, user: new_user_object)
#
@@ -94,10 +95,11 @@
#
# CanTakeABlock.call { |result| service_result = result }
# service_result
# #=> :the_service_result
#
+ # @note See README section "Running Callbacks"
class Service
include ProvidesCallbacks
include ServiceCaller
# The default :not_authorized callback
@@ -187,28 +189,31 @@
not_authorized: CB_NOT_AUTHORIZED, **inputs)
self.context = context
self.logger = logger
self.not_authorized = not_authorized
self.inputs = inputs
+ self.stop_caller = false
end
def call
validate_service_definition
catch(:stop) do
authorize
log_service_call
main
self.block_result = yield result if block_given?
end
+ throw :stop if stop_caller
return block_result if block_given?
return result if result_set?
self
end
private
- attr_accessor :context, :logger, :not_authorized, :block_result
+ attr_accessor :context, :logger, :not_authorized, :block_result,
+ :stop_caller
attr_writer :result
attr_reader :inputs
alias service_context context
alias service_logger logger
@@ -241,12 +246,12 @@
def authorize
return if authorized?
logger.warn("Unauthorized attempt to access #{self.class.name} " \
"as #{context.inspect}")
- not_authorized.call(service: self.class, context: context)
- throw :stop
+ run_callback(not_authorized, service: self.class, context: context)
+ stop!
end
def stop!
throw :stop
end
@@ -256,8 +261,17 @@
@result
end
def result_set?
defined?(@result)
+ end
+
+ def run_callback(callback, *args)
+ continue = false
+ continue = catch(:stop) do
+ callback.call(*args)
+ true
+ end
+ self.stop_caller ||= !continue
end
end
end