Skip to content

Commit

Permalink
Merge pull request rails#53440 from fatkodima/current_attributes-new-…
Browse files Browse the repository at this point in the history
…object

Fix `CurrentAttributes#attributes` to return new object each time
  • Loading branch information
byroot authored Oct 24, 2024
2 parents 7fac5d1 + 90a96b8 commit c8ad2b2
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 3 deletions.
6 changes: 6 additions & 0 deletions activesupport/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
* `ActiveSupport::CurrentAttributes#attributes` now will return a new hash object on each call.

Previously, the same hash object was returned each time that method was called.

*fatkodima*

* `ActiveSupport::JSON.encode` supports CIDR notation.

Previously:
Expand Down
10 changes: 7 additions & 3 deletions activesupport/lib/active_support/current_attributes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,13 @@ def attribute(*names, default: NOT_SET)
owner.define_cached_method(name, namespace: :current_attributes) do |batch|
batch <<
"def #{name}" <<
"attributes[:#{name}]" <<
"@attributes[:#{name}]" <<
"end"
end
owner.define_cached_method("#{name}=", namespace: :current_attributes) do |batch|
batch <<
"def #{name}=(value)" <<
"attributes[:#{name}] = value" <<
"@attributes[:#{name}] = value" <<
"end"
end
end
Expand Down Expand Up @@ -194,12 +194,16 @@ def method_added(name)

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

attr_accessor :attributes
attr_writer :attributes

def initialize
@attributes = resolve_defaults
end

def attributes
@attributes.dup
end

# Expose one or more attributes within a block. Old values are returned after the block concludes.
# Example demonstrating the common use of needing to set Current attributes outside the request-cycle:
#
Expand Down
4 changes: 4 additions & 0 deletions activesupport/test/current_attributes_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -251,6 +251,10 @@ def after_teardown
assert_equal({ counter_integer: 0, counter_callable: 0 }, Current.attributes)
end

test "#attributes returns different objects each time" do
assert_not_same Current.attributes, Current.attributes
end

test "CurrentAttributes restricted attribute names" do
assert_raises ArgumentError, match: /Restricted attribute names: reset, set/ do
class InvalidAttributeNames < ActiveSupport::CurrentAttributes
Expand Down

0 comments on commit c8ad2b2

Please sign in to comment.