Class: ServiceObjects::Message

Inherits:
Object
  • Object
show all
Includes:
Comparable
Defined in:
lib/service_objects/message.rb

Overview

Describes messages published by service objects

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#priorityFloat (readonly)

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.



29
30
31
32
# File 'lib/service_objects/message.rb', line 29

def priority
  return @custom_priority.to_f if @custom_priority
  type == "error" ? -1.0 : 0.0
end

#textString (readonly)

The text of the message



20
21
22
# File 'lib/service_objects/message.rb', line 20

def text
  @text
end

#typeString (readonly)

The type of the message



14
15
16
# File 'lib/service_objects/message.rb', line 14

def type
  @type
end

Class Method Details

.initialize(type:, text:, priority: nil) ⇒ ServiceObjects::Message

Constructs and freezes the message object

Examples:

Message.new type: "info", text: "foo", priority: 3


48
49
50
51
52
53
# File 'lib/service_objects/message.rb', line 48

def initialize(type:, text:, priority: nil)
  @type = type.to_s.freeze
  @text = text.to_s.freeze
  @custom_priority = priority
  freeze
end

Instance Method Details

#<=>(other) ⇒ -1, ...

Compares the message with the other object



75
76
77
78
79
80
# File 'lib/service_objects/message.rb', line 75

def <=>(other)
  return unless other.is_a? self.class
  [:priority, :type, :text]
    .map { |key| __compare_to__ other, by: key }
    .detect { |value| value } || 0
end

#==(other) ⇒ true, false

Checks equality of the message to the other object



63
64
65
# File 'lib/service_objects/message.rb', line 63

def ==(other)
  (self <=> other) == 0
end

#inspectString

A human-readable representation of the message



99
100
101
102
103
104
105
106
# File 'lib/service_objects/message.rb', line 99

def inspect
  %W(
    #<ServiceObjects::Message:#{ object_id }
    type=\"#{ type }\"
    text=\"#{ text }\"
    priority=#{ priority }>
  ).join(" ")
end

#new(type:, text:, priority:) ⇒ ServiceObjects::Message

Constructs and freezes the message object

Examples:

Message.new type: "info", text: "foo", priority: 3


48
49
50
51
52
53
# File 'lib/service_objects/message.rb', line 48

def initialize(type:, text:, priority: nil)
  @type = type.to_s.freeze
  @text = text.to_s.freeze
  @custom_priority = priority
  freeze
end

#to_hHash

Converts the message object to hash



85
86
87
# File 'lib/service_objects/message.rb', line 85

def to_h
  { type: type, text: text }
end

#to_jsonString

Converts the message object to json



92
93
94
# File 'lib/service_objects/message.rb', line 92

def to_json
  to_h.to_json
end