Skip to content

Commit

Permalink
Added ability to modify payload within block
Browse files Browse the repository at this point in the history
When instrumenting a block of code, it is sometimes useful for that
block to add more things to the payload. A common example is when
performing an http request, it is useful to include the response status
code in the instrumentation.

```
instrument("example.request", url: url, body: body) do |payload|
  response = http.post(url, params: body)
  payload[:response] = response
end
```

This change simply yields the payload to the block to enable this.

NOTE: If the instrument method is called with no overriding payload, the
payload yielded to the block is the default EMPTY_HASH that is frozen,
which results in a FrozenError if the block attempts to add anything to
the hash.
  • Loading branch information
paul committed Jan 21, 2021
1 parent 3102061 commit 21a2ff2
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
2 changes: 1 addition & 1 deletion lib/dry/monitor/notifications.rb
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def stop(event_id, payload)
end

def instrument(event_id, payload = EMPTY_HASH)
result, time = @clock.measure { yield } if block_given?
result, time = @clock.measure { yield payload } if block_given?

process(event_id, payload) do |event, listener|
if time
Expand Down
16 changes: 16 additions & 0 deletions spec/integration/instrumentation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,21 @@

expect(captured).to eql([[:sql]])
end

it 'yields the payload to the instrumented block' do
captured = []

notifications.subscribe(:sql) do |event|
captured << event
end

notifications.instrument(:sql, outside_block: true) do |payload|
payload[:inside_block] = true
end

expect(captured[0].payload).to match hash_including(
outside_block: true, inside_block: true
)
end
end
end

0 comments on commit 21a2ff2

Please sign in to comment.