Skip to content

Commit 7edf988

Browse files
authored
Merge pull request rails#50678 from seanpdoyle/current-attributes-with
Implement `CurrentAttributes#set` in terms of `Object#with`
2 parents d8cb2e9 + 3c72983 commit 7edf988

File tree

2 files changed

+9
-15
lines changed

2 files changed

+9
-15
lines changed

activesupport/lib/active_support/current_attributes.rb

Lines changed: 3 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# frozen_string_literal: true
22

33
require "active_support/callbacks"
4+
require "active_support/core_ext/object/with"
45
require "active_support/core_ext/enumerable"
56
require "active_support/core_ext/module/delegation"
67

@@ -207,12 +208,8 @@ def initialize
207208
# end
208209
# end
209210
# end
210-
def set(set_attributes)
211-
old_attributes = compute_attributes(set_attributes.keys)
212-
assign_attributes(set_attributes)
213-
yield
214-
ensure
215-
assign_attributes(old_attributes)
211+
def set(attributes, &block)
212+
with(**attributes, &block)
216213
end
217214

218215
# Reset all attributes. Should be called before and after actions, when used as a per-request singleton.
@@ -221,14 +218,5 @@ def reset
221218
self.attributes = {}
222219
end
223220
end
224-
225-
private
226-
def assign_attributes(new_attributes)
227-
new_attributes.each { |key, value| public_send("#{key}=", value) }
228-
end
229-
230-
def compute_attributes(keys)
231-
keys.index_with { |key| public_send(key) }
232-
end
233221
end
234222
end

activesupport/test/current_attributes_test.rb

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,12 @@ def after_teardown
144144

145145
assert_equal "world/1", Current.world
146146
assert_equal "account/1", Current.account
147+
148+
hash = { world: "world/2", account: "account/2" }
149+
Current.set(hash) do
150+
assert_equal "world/2", Current.world
151+
assert_equal "account/2", Current.account
152+
end
147153
end
148154

149155
test "using keyword arguments" do

0 commit comments

Comments
 (0)