File tree Expand file tree Collapse file tree 2 files changed +19
-3
lines changed Expand file tree Collapse file tree 2 files changed +19
-3
lines changed Original file line number Diff line number Diff line change @@ -96,13 +96,15 @@ def update_context(**options)
96
96
end
97
97
98
98
# Updates the context used to construct tags in the SQL comment during
99
- # execution of the provided block. Resets provided values to nil after
100
- # the block is executed .
99
+ # execution of the provided block. Resets the provided keys to their
100
+ # previous value once the block exits .
101
101
def set_context ( **options )
102
+ keys = options . keys
103
+ previous_context = keys . zip ( context . values_at ( *keys ) ) . to_h
102
104
update_context ( **options )
103
105
yield if block_given?
104
106
ensure
105
- update_context ( **options . transform_values! { NullObject . new } )
107
+ update_context ( **previous_context )
106
108
end
107
109
108
110
# Temporarily tag any query executed within `&block`. Can be nested.
Original file line number Diff line number Diff line change @@ -253,4 +253,18 @@ def test_custom_proc_context_tags
253
253
ActiveRecord ::QueryLogs . update_context ( foo : nil )
254
254
ActiveRecord ::QueryLogs . tags = original_tags
255
255
end
256
+
257
+ def test_set_context_restore_state
258
+ original_tags = ActiveRecord ::QueryLogs . tags
259
+ ActiveRecord ::QueryLogs . tags = [ foo : -> { context [ :foo ] } ]
260
+ ActiveRecord ::QueryLogs . set_context ( foo : "bar" ) do
261
+ assert_sql ( %r{/\* foo:bar\* /$} ) { Dashboard . first }
262
+ ActiveRecord ::QueryLogs . set_context ( foo : "plop" ) do
263
+ assert_sql ( %r{/\* foo:plop\* /$} ) { Dashboard . first }
264
+ end
265
+ assert_sql ( %r{/\* foo:bar\* /$} ) { Dashboard . first }
266
+ end
267
+ ensure
268
+ ActiveRecord ::QueryLogs . tags = original_tags
269
+ end
256
270
end
You can’t perform that action at this time.
0 commit comments