Module: Stoplight::Infrastructure::Notifier::Generic

Included in:
IO, Logger
Defined in:
lib/stoplight/infrastructure/notifier/generic.rb

Overview

The Generic module provides a reusable implementation for notifiers in Stoplight. It includes a formatter for generating notification messages and defines the notify method.

Examples:

Custom Notifier Implementation and Usage

# Custom notifier that writes notifications to a file
class FileNotifier < Stoplight::Domain::StateTransitionNotifier
  include Stoplight::Notifier::Generic

  def initialize(file_path)
    @file = File.open(file_path, 'a')
    super(@file)
  end

  private

  # Writes the notification message to the file
  def put(message)
    @file.puts(message)
  end
end

# Usage example
# Create a custom notifier that writes to 'stoplight.log'
notifier = FileNotifier.new('stoplight.log')

# Configure Stoplight to use the custom notifier
Stoplight.configure do |config|
  config.notifiers += [notifier]
end

# Create a stoplight and trigger a state change
light = Stoplight('example-light')
light.run { raise 'Simulated failure' } rescue nil
light.run { raise 'Simulated failure' } rescue nil
light.run { raise 'Simulated failure' } rescue nil

Constant Summary collapse

DEFAULT_FORMATTER =
lambda do |light, from_color, to_color, error|
  words = ["Switching", light.name, "from", from_color, "to", to_color]
  words += ["because", error.class, error.message] if error
  words.join(" ")
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#formatterObject (readonly)

The formatter used to generate notification messages.



44
45
46
# File 'lib/stoplight/infrastructure/notifier/generic.rb', line 44

def formatter
  @formatter
end

Instance Method Details

#initialize(object, formatter = nil) ⇒ Object

Parameters:

  • object

    The object used by the notifier (e.g., a logger or external service).

  • formatter (defaults to: nil)

    A custom formatter for generating notification messages. If no formatter is provided, the default formatter is used.



56
57
58
59
# File 'lib/stoplight/infrastructure/notifier/generic.rb', line 56

def initialize(object, formatter = nil)
  @object = object
  @formatter = formatter || DEFAULT_FORMATTER
end

#notify(light, from_color, to_color, error) ⇒ Object

Sends a notification when a Stoplight changes state.



62
63
64
65
66
# File 'lib/stoplight/infrastructure/notifier/generic.rb', line 62

def notify(light, from_color, to_color, error)
  message = formatter.call(light, from_color, to_color, error)
  put(message)
  message
end