Sha256: 0a526e4d0d07f59417330868bfb693e2fc2c0d98b958d479315fd2f23e9c3751

Contents?: true

Size: 1.95 KB

Versions: 2

Compression:

Stored size: 1.95 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

      # Distinguishes two messages by type and text.
      #
      # @example
      #     a = Message.new(type: "a", text: "a")
      #     b = Message.new(type: "a", text: "a")
      #     c = Message.new(type: "b", text: "a")
      #     d = Message.new(type: "a", text: "b")
      #
      #     a == b # => true
      #     a == c # => false
      #     a == d # => false
      #
      # Params:
      # +other+:: other message to distinguish from.
      #
      def ==(other)
        return false unless other.is_a? self.class
        [type, text] == [other.type, other.text]
      end

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
hexx-2.2.0 lib/hexx/service/message.rb
hexx-2.1.0 lib/hexx/service/message.rb