Class: Message

Inherits:
Object
  • Object
show all
Defined in:
lib/utils/message.rb

Overview

The Message class represents a mechanism for dynamically handling and formatting messages.

It supports the substitution of placeholders within a message template with actual data.

The class leverages file-based message templates, allowing for easy localization or customization of messages.

It integrates seamlessly with the Resources module to access these templates from a customizable path set via the "SCRIPT_CUSTOM_RESOURCES" environment variable or from a default library path.

Examples:

Creating a new Message instance and formatting it

# Assuming "hellow_world" is a file that says "Hello, world!"
message = Message.new("hellow_world")
puts message.to_s # => "Hello, world!"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(message, replaces: nil) ⇒ Message

Initializes a new instance of the Message class with a given message template.

Parameters:

  • message (String)

    The message template to be used.

  • replaces (Hash) (defaults to: nil)

    Used to replace all occurrences of a key with its value.



28
29
30
31
32
33
# File 'lib/utils/message.rb', line 28

def initialize(message, replaces: nil)
  raise 'Messsage replaces content need be a Hash' if !replaces.nil? && !replaces.is_a?(Hash)

  @to_replace = replaces
  @message = message
end

Instance Attribute Details

#messageObject (readonly)

Returns the value of attribute message.



22
23
24
# File 'lib/utils/message.rb', line 22

def message
  @message
end

Instance Method Details

#==(other) ⇒ Boolean

Compares two Message instances for equality based on their message content.

Parameters:

  • other (Message)

    The other Message instance to compare with.

Returns:

  • (Boolean)

    True if the messages are equal, otherwise false.



39
40
41
# File 'lib/utils/message.rb', line 39

def ==(other)
  self.class == other.class && @message == other.message
end

#to_sString

Converts the message template into a string, replacing any placeholders with actual data. This method searches for keys within the message and replaces them with corresponding content from message files located in either the custom path or the library path and appling the given replaces.

Returns:

  • (String)

    The formatted message with placeholders substituted with actual content.



49
50
51
52
# File 'lib/utils/message.rb', line 49

def to_s
  new_message = replace_message_keys(String.new(@message))
  replace_all_to_replace_elements(new_message)
end