Skip to content

Commit c8ad2b2

Browse files
authored
Merge pull request rails#53440 from fatkodima/current_attributes-new-object
Fix `CurrentAttributes#attributes` to return new object each time
2 parents 7fac5d1 + 90a96b8 commit c8ad2b2

File tree

3 files changed

+17
-3
lines changed

3 files changed

+17
-3
lines changed

activesupport/CHANGELOG.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,9 @@
1+
* `ActiveSupport::CurrentAttributes#attributes` now will return a new hash object on each call.
2+
3+
Previously, the same hash object was returned each time that method was called.
4+
5+
*fatkodima*
6+
17
* `ActiveSupport::JSON.encode` supports CIDR notation.
28

39
Previously:

activesupport/lib/active_support/current_attributes.rb

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -122,13 +122,13 @@ def attribute(*names, default: NOT_SET)
122122
owner.define_cached_method(name, namespace: :current_attributes) do |batch|
123123
batch <<
124124
"def #{name}" <<
125-
"attributes[:#{name}]" <<
125+
"@attributes[:#{name}]" <<
126126
"end"
127127
end
128128
owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch|
129129
batch <<
130130
"def #{name}=(value)" <<
131-
"attributes[:#{name}] = value" <<
131+
"@attributes[:#{name}] = value" <<
132132
"end"
133133
end
134134
end
@@ -194,12 +194,16 @@ def method_added(name)
194194

195195
class_attribute :defaults, instance_writer: false, default: {}.freeze
196196

197-
attr_accessor :attributes
197+
attr_writer :attributes
198198

199199
def initialize
200200
@attributes = resolve_defaults
201201
end
202202

203+
def attributes
204+
@attributes.dup
205+
end
206+
203207
# Expose one or more attributes within a block. Old values are returned after the block concludes.
204208
# Example demonstrating the common use of needing to set Current attributes outside the request-cycle:
205209
#

activesupport/test/current_attributes_test.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -251,6 +251,10 @@ def after_teardown
251251
assert_equal({ counter_integer: 0, counter_callable: 0 }, Current.attributes)
252252
end
253253

254+
test "#attributes returns different objects each time" do
255+
assert_not_same Current.attributes, Current.attributes
256+
end
257+
254258
test "CurrentAttributes restricted attribute names" do
255259
assert_raises ArgumentError, match: /Restricted attribute names: reset, set/ do
256260
class InvalidAttributeNames < ActiveSupport::CurrentAttributes

0 commit comments

Comments
 (0)