Skip to content

Commit 9b94ec1

Browse files
authored
Add support for Sync(annotation:). (#348)
1 parent 72fae62 commit 9b94ec1

File tree

4 files changed

+41
-7
lines changed

4 files changed

+41
-7
lines changed

gems.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
end
2121

2222
group :test do
23-
gem "sus", "~> 0.29", ">= 0.29.1"
23+
gem "sus", "~> 0.31"
2424
gem "covered"
2525
gem "decode"
2626
gem "rubocop"

lib/kernel/sync.rb

+7-3
Original file line numberDiff line numberDiff line change
@@ -15,17 +15,21 @@ module Kernel
1515
#
1616
# @public Since `stable-v1`.
1717
# @asynchronous Will block until given block completes executing.
18-
def Sync(&block)
18+
def Sync(annotation: nil, &block)
1919
if task = ::Async::Task.current?
20-
yield task
20+
if annotation
21+
task.annotate(annotation) {yield task}
22+
else
23+
yield task
24+
end
2125
elsif scheduler = Fiber.scheduler
2226
::Async::Task.run(scheduler, &block).wait
2327
else
2428
# This calls Fiber.set_scheduler(self):
2529
reactor = Async::Reactor.new
2630

2731
begin
28-
return reactor.run(finished: ::Async::Condition.new, &block).wait
32+
return reactor.run(annotation: annotation, finished: ::Async::Condition.new, &block).wait
2933
ensure
3034
Fiber.set_scheduler(nil)
3135
end

test/kernel/async.rb

+4
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,10 @@
1717
Async(transient: true) do |task|
1818
expect(task).to be(:transient?)
1919
end
20+
21+
Async(annotation: 'foobar') do |task|
22+
expect(task.annotation).to be == 'foobar'
23+
end
2024
end
2125
end
2226
end

test/kernel/sync.rb

+29-3
Original file line numberDiff line numberDiff line change
@@ -21,19 +21,45 @@
2121

2222
expect(result).to be == value
2323
end
24-
24+
25+
it "passes annotation through to initial task" do
26+
Sync(annotation: 'foobar') do |task|
27+
expect(task.annotation).to be == 'foobar'
28+
end
29+
end
30+
2531
it "can run inside reactor" do
2632
Async do |task|
2733
result = Sync do |sync_task|
2834
expect(Async::Task.current).to be == task
2935
expect(sync_task).to be == task
30-
36+
3137
next value
3238
end
33-
39+
3440
expect(result).to be == value
3541
end
3642
end
43+
44+
with "parent task" do
45+
it "replaces and restores existing task's annotation" do
46+
annotations = []
47+
48+
Async(annotation: "foo") do |t1|
49+
annotations << t1.annotation
50+
51+
Sync(annotation: "bar") do |t2|
52+
expect(t2).to be_equal(t1)
53+
annotations << t1.annotation
54+
end
55+
56+
annotations << t1.annotation
57+
end.wait
58+
59+
expect(annotations).to be == %w[foo bar foo]
60+
end
61+
end
62+
3763

3864
it "can propagate error without logging them" do
3965
expect(Console).not.to receive(:error)

0 commit comments

Comments
 (0)