Class: WaterDrop::Middleware

Inherits:
Object
  • Object
show all
Defined in:
lib/waterdrop/middleware.rb

Overview

Simple middleware layer for manipulating messages prior to their validation

Instance Method Summary collapse

Constructor Details

#initializeMiddleware

Returns a new instance of Middleware.



6
7
8
9
10
# File 'lib/waterdrop/middleware.rb', line 6

def initialize
  @mutex = Mutex.new
  @steps = []
  @count = 0
end

Instance Method Details

#append(step) ⇒ Object

Register given middleware as the last one in the chain

Parameters:

  • step (#call)

    step that needs to return the message



56
57
58
59
60
61
# File 'lib/waterdrop/middleware.rb', line 56

def append(step)
  @mutex.synchronize do
    @steps.append step
    @count = @steps.size
  end
end

#prepend(step) ⇒ Object

Register given middleware as the first one in the chain

Parameters:

  • step (#call)

    step that needs to return the message



47
48
49
50
51
52
# File 'lib/waterdrop/middleware.rb', line 47

def prepend(step)
  @mutex.synchronize do
    @steps.prepend step
    @count = @steps.size
  end
end

#run(message) ⇒ Hash

Note:

You need to decide yourself whether you don’t use the message hash data anywhere else and you want to save on memory by modifying it in place or do you want to do a deep copy

Runs middleware on a single message prior to validation

Parameters:

  • message (Hash)

    message hash

Returns:

  • (Hash)

    message hash. Either the same if transformed in place, or a copy if modified into a new object.



19
20
21
22
23
24
25
26
27
# File 'lib/waterdrop/middleware.rb', line 19

def run(message)
  return message if @count.zero?

  @steps.each do |step|
    message = step.call(message)
  end

  message
end

#run_many(messages) ⇒ Array<Hash>

Returns transformed messages or same messages if no transformation.

Parameters:

  • messages (Array<Hash>)

    messages on which we want to run middlewares

Returns:

  • (Array<Hash>)

    transformed messages or same messages if no transformation



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/waterdrop/middleware.rb', line 31

def run_many(messages)
  # Skip middleware processing entirely if no middleware steps are configured
  return messages if @count.zero?

  # Use each_with_object to avoid creating intermediate arrays for large batches
  messages.each_with_object([]) do |message, result|
    @steps.each do |step|
      message = step.call(message)
    end

    result << message
  end
end