# encoding: utf-8 require "json" module ServiceObjects # Describes messages published by service objects class Message include Comparable # @!attribute [r] type # The type of the message # # @return [String] attr_reader :type # @!attribute [r] text # The text of the message # # @return [String] attr_reader :text # @!attribute [r] priority # The priority level for the message # # If priority hasn't been set on initialization, sets it to -1.0 for errors, # or 0.0 otherwise. # # @return [Float] def priority return @custom_priority.to_f if @custom_priority type == "error" ? -1.0 : 0.0 end # @!scope class # @!method new(type:, text:, priority:) # Constructs and freezes the message object # # @example # Message.new type: "info", text: "foo", priority: 3 # # @param [#to_s] type # @param [#to_s] text # @param [#to_f] priority # optional custom priority of the message (the less the higher) # # @return [ServiceObjects::Message] # the frozen message object def initialize(type:, text:, priority: nil) @type = type.to_s.freeze @text = text.to_s.freeze @custom_priority = priority freeze end # Checks equality of the message to the other object # # @param [Object] other # # @return [true] # if messages has the same attributes # @return [false] # if the other object is not a message or has different argument(s) def ==(other) (self <=> other) == 0 end # Compares the message with the other object # # @param [Object] other # # @return [-1, 0, 1] # if the argument is a message # @return [nil] # if the other object is not a message def <=>(other) return unless other.is_a? self.class [:priority, :type, :text] .map { |key| __compare_to__ other, by: key } .detect { |value| value } || 0 end # Converts the message object to hash # # @return [Hash] def to_h { type: type, text: text } end # Converts the message object to json # # @return [String] def to_json to_h.to_json end # A human-readable representation of the message # # @return [String] def inspect %W( # ).join(" ") end private def __compare_to__(other, by:) value = (send(by) <=> other.send(by)) value == 0 ? nil : value end end # class Message end # module ServiceObjects