Skip to content

Commit 9c712f8

Browse files
authored
Merge pull request rails#50470 from seanpdoyle/object-with-block-argument
Yield instance to `Object#with` block
2 parents cbeafdf + 9e64b13 commit 9c712f8

File tree

3 files changed

+19
-3
lines changed

3 files changed

+19
-3
lines changed

activesupport/CHANGELOG.md

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,13 @@
1+
* Yield instance to `Object#with` block
2+
3+
```ruby
4+
client.with(timeout: 5_000) do |c|
5+
c.get("/commits")
6+
end
7+
```
8+
9+
*Sean Doyle*
10+
111
* Use logical core count instead of physical core count to determine the
212
default number of workers when parallelizing tests.
313

activesupport/lib/active_support/core_ext/object/with.rb

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,13 @@ class Object
44
# Set and restore public attributes around a block.
55
#
66
# client.timeout # => 5
7-
# client.with(timeout: 1) do
8-
# client.timeout # => 1
7+
# client.with(timeout: 1) do |c|
8+
# c.timeout # => 1
99
# end
1010
# client.timeout # => 5
1111
#
12+
# The receiver is yielded to the provided block.
13+
#
1214
# This method is a shorthand for the common begin/ensure pattern:
1315
#
1416
# old_value = object.attribute
@@ -28,7 +30,7 @@ def with(**attributes)
2830
old_values[key] = public_send(key)
2931
public_send("#{key}=", value)
3032
end
31-
yield
33+
yield self
3234
ensure
3335
old_values.each do |key, old_value|
3436
public_send("#{key}=", old_value)

activesupport/test/core_ext/object/with_test.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,10 @@ def initialize
8888
assert_equal :mixed, @object.mixed_attr
8989
end
9090

91+
test "yields the instance to the block" do
92+
assert_equal "1", @object.with(public_attr: "1", &:public_attr)
93+
end
94+
9195
test "basic immediates don't respond to #with" do
9296
assert_not_respond_to nil, :with
9397
assert_not_respond_to true, :with

0 commit comments

Comments
 (0)