Sha256: 2d5fd8ab52f0debd8e6e38c8f98b7ba48d4916add4024efdd755d8723ea0c88e

Contents?: true

Size: 1.47 KB

Versions: 3

Compression:

Stored size: 1.47 KB

Contents

module Hexx
  class Service

    # A message to be returned by services.
    class Message
      include Comparable

      # A stringified type and a text of the message.
      attr_reader :type, :text

      # Initializes the message.
      #
      # @example
      #     Message.new type: "success", text: "Object created!"
      #
      # Params:
      # <tt>:type</tt>:: string/symbolic message type (:error, :info, :success).
      # <tt>:text</tt>:: message text.
      #
      def initialize(type:, text:)
        @type, @text = type.to_s, text.to_s
      end

      # Extracts error messages from ActiveRecord or ActiveModel objects.
      #
      # @example
      #     Message.from(object) # => [#<Hexx::Service::Message ...>]
      #
      # Params:
      # +object+:: an object to extract messages from.
      #
      def self.from(object)
        object.errors.values.flatten.map do |text|
          new type: "error", text: text
        end
      end

      # Compares two messages by type and text.
      def ==(other)
        return false unless other.is_a? self.class
        [type, text] == [other.type, other.text]
      end

      # Orders messages by type and text.
      #
      # @example
      #     ab = Message.new(type: "a", text: "b")
      #     ba = Message.new(type: "b", text: "a")
      #     ab < ba # => true
      #
      def <=>(other)
        fail ArgumentError unless other.is_a? self.class
        [type, text] <=> [other.type, other.text]
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
hexx-2.0.2 lib/hexx/service/message.rb
hexx-2.0.1 lib/hexx/service/message.rb
hexx-2.0.0 lib/hexx/service/message.rb