Class: Lumberjack::Formatter::IdFormatter

Inherits:
Object
  • Object
show all
Defined in:
lib/lumberjack/formatter/id_formatter.rb

Overview

Format an object that has an id as a hash with keys for class and id. This formatter is useful as a default formatter for objects pulled from a data store. By default it will use :id as the id attribute.

The formatter creates a standardized representation of objects by extracting their class name and identifier, making it easy to identify objects in logs without exposing all their data. This is particularly useful for ActiveRecord models, database objects, or any objects that have a unique identifier attribute.

Instance Method Summary collapse

Constructor Details

#initialize(id_attribute = :id) ⇒ IdFormatter

Returns a new instance of IdFormatter.

Parameters:

  • id_attribute (Symbol, String) (defaults to: :id)

    The attribute to use as the id (defaults to :id).



17
18
19
# File 'lib/lumberjack/formatter/id_formatter.rb', line 17

def initialize(id_attribute = :id)
  @id_attribute = id_attribute
end

Instance Method Details

#call(obj) ⇒ Hash, String

Format an object by extracting its class name and ID attribute.

Parameters:

  • obj (Object)

    The object to format. Must respond to the configured ID attribute.

Returns:

  • (Hash, String)

    A hash with "class" and "id" keys if the object has the ID attribute, otherwise returns the object's string representation.



26
27
28
29
30
31
32
33
# File 'lib/lumberjack/formatter/id_formatter.rb', line 26

def call(obj)
  if obj.respond_to?(@id_attribute)
    id = obj.send(@id_attribute)
    {"class" => obj.class.name, "id" => id}
  else
    obj.to_s
  end
end