Module: CMDx::Utils::Format

Extended by:
Format
Included in:
Format
Defined in:
lib/cmdx/utils/format.rb

Overview

Utility module for formatting data structures into log-friendly strings and converting messages to appropriate formats for logging

Instance Method Summary collapse

Instance Method Details

#to_log(message) ⇒ Hash, Object

Converts a message to a format suitable for logging

Examples:

Hash like objects

Format.to_log({user_id: 123, action: "login"})
# => {user_id: 123, action: "login"}

Simple message

Format.to_log("simple message")
# => "simple message"

CMDx object

Format.to_log(CMDx::Task.new(name: "task1"))
# => {name: "task1"}

Parameters:

  • message (Object)

    The message to format

Returns:

  • (Hash, Object)

    Returns a hash if the message responds to to_h and is a CMDx object, otherwise returns the original message



34
35
36
37
38
39
40
# File 'lib/cmdx/utils/format.rb', line 34

def to_log(message)
  if message.respond_to?(:to_h) && message.class.ancestors.any? { |a| a.to_s.start_with?("CMDx") }
    message.to_h
  else
    message
  end
end

#to_str(hash, &block) ⇒ String

Converts a hash to a formatted string using a custom formatter

Examples:

Default formatter

Format.to_str({user_id: 123, status: "active"})
# => "user_id=123 status=\"active\""

Custom formatter

Format.to_str({count: 5, total: 100}) { |k, v| "#{k}:#{v}" }
# => "count:5 total:100"

Parameters:

  • hash (Hash)

    The hash to convert to string

  • block (Proc, nil)

    Optional custom formatter block

Returns:

  • (String)

    Space-separated formatted key-value pairs



59
60
61
62
# File 'lib/cmdx/utils/format.rb', line 59

def to_str(hash, &block)
  block ||= FORMATTER
  hash.map(&block).join(" ")
end