Class: WaterDrop::Middleware
- Inherits:
-
Object
- Object
- WaterDrop::Middleware
- Defined in:
- lib/waterdrop/middleware.rb
Overview
Simple middleware layer for manipulating messages prior to their validation
Instance Method Summary collapse
-
#append(step) ⇒ Object
Register given middleware as the last one in the chain.
-
#initialize ⇒ Middleware
constructor
Creates a new middleware chain with no registered steps.
-
#prepend(step) ⇒ Object
Register given middleware as the first one in the chain.
-
#run(message) ⇒ Hash
Runs middleware on a single message prior to validation.
-
#run_many(messages) ⇒ Array<Hash>
Transformed messages or same messages if no transformation.
Constructor Details
#initialize ⇒ Middleware
Creates a new middleware chain with no registered steps
7 8 9 10 11 |
# File 'lib/waterdrop/middleware.rb', line 7 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
57 58 59 60 61 62 |
# File 'lib/waterdrop/middleware.rb', line 57 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
48 49 50 51 52 53 |
# File 'lib/waterdrop/middleware.rb', line 48 def prepend(step) @mutex.synchronize do @steps.prepend step @count = @steps.size end end |
#run(message) ⇒ Hash
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
20 21 22 23 24 25 26 27 28 |
# File 'lib/waterdrop/middleware.rb', line 20 def run() return if @count.zero? @steps.each do |step| = step.call() end end |
#run_many(messages) ⇒ Array<Hash>
Returns transformed messages or same messages if no transformation.
32 33 34 35 36 37 38 39 40 41 42 43 44 |
# File 'lib/waterdrop/middleware.rb', line 32 def run_many() # Skip middleware processing entirely if no middleware steps are configured return if @count.zero? # Use each_with_object to avoid creating intermediate arrays for large batches .each_with_object([]) do |, result| @steps.each do |step| = step.call() end result << end end |