lib/hexx/service.rb in hexx-3.2.0 vs lib/hexx/service.rb in hexx-3.2.1
- old
+ new
@@ -119,10 +119,29 @@
# The decorator that allows access to the service's private methods.
def with_callbacks(prefix: nil)
WithCallbacks.new(self, prefix: prefix)
end
+ # @!attribute [r] messages
+ # The array of service messages (instances of {Hexx::Service::Message})
+ # with +text+ and +type+ attributes.
+ #
+ # @example
+ # class Test < Hexx::Service
+ # def run
+ # add_message "info", :ok
+ # end
+ # end
+ #
+ # service = Test.new
+ # service.run # adds message
+ # service.messages
+ # # => [#<Hexx::Service::Message @text="ok" @type="info" >]
+ #
+ # @return [Array<Hexx::Service::Message>] The array of messages.
+ attr_reader :messages
+
private
# The helper runs another service object and subscribes +self+ for the
# service object's notifications.
#
@@ -165,36 +184,36 @@
service.run
end
# @!method escape
#
- # The method rescues block runtime errors and publishes the :error
- # notification.
+ # The method:
+ # * rescues +StandardError+ exceptions
+ # * adds error message to the service
+ # * re-raises the <tt>Service::Invalid</tt> exception
#
# @example
# class GetItem < Hexx::Service
# def run
- # escape do
- # errors.add :base, :error
- # fail Invalid.new self
- # end
+ # escape { do_something_unsafe }
+ # rescue => err
+ # publish :error, err.messages
# end
+ # publish :success
+ # end
# end
#
- # service = GetItem.new
- # service.subscribe listener
- # service.run
- # # => the listener will be sent the error(messages).
- #
# @yield the block.
+ # @raise [Hexx::Service::Invalid] if the block raised the +StandardError+.
# @return the value returned by the block.
def escape
yield
- rescue Service::Invalid => err
- publish :error, Message.from(err.service)
+ rescue Invalid => err
+ raise err
rescue => err
- publish :error, [Message.new(type: "error", text: err.message)]
+ errors.add :base, err.message
+ raise Invalid.new(self)
end
# Translates given key in current service's scope.
#
# @note The method uses I18n.t library method.
@@ -218,27 +237,10 @@
return text unless text.is_a? Symbol
scope = %w(activemodel messages models) << self.class.name.underscore
I18n.t text, options.merge(scope: scope)
end
- # @!attribute messages
- # The array of service messages, added by the {#add_message} helper.
- #
- # @example
- # class Test < Hexx::Service
- # def run
- # add_message "info", :ok
- # messages
- # end
- # end
- # result = Test.new.run.first
- # result.type
- # # => "info"
- # result.text
- # # => "translation not found: en.activemodel.messages.models.test.ok"
- #
- # @return [Array<Hexx::Service::Message>] The array of message objects.
- attr_accessor :messages
+ attr_writer :messages
# Adds the translated message to the {#messages} array.
# @example (see Service#messages)
# @param [String] type The type of the message ("error", "info", "success")
# @param [String, Symbol] text The text of the message. The symbol will