Skip to content

Commit 44856ef

Browse files
committed
Add instance#to_json and #as_json for serialization.
1 parent dd7f1ef commit 44856ef

File tree

3 files changed

+48
-4
lines changed

3 files changed

+48
-4
lines changed

fixtures/async/container/a_container.rb

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,27 @@ module Container
8787
expect(input.read).to be == "true"
8888
end
8989

90+
with "instance" do
91+
it "can generate JSON representation" do
92+
IO.pipe do |input, output|
93+
container.spawn do |instance|
94+
output.write(instance.to_json)
95+
end
96+
97+
container.wait
98+
99+
expect(container.statistics).to have_attributes(failures: be == 0)
100+
101+
output.close
102+
instance = JSON.parse(input.read, symbolize_names: true)
103+
expect(instance).to have_keys(
104+
process_id: be_a(Integer),
105+
name: be_a(String),
106+
)
107+
end
108+
end
109+
end
110+
90111
with "#sleep" do
91112
it "can sleep for a short time" do
92113
container.spawn do

lib/async/container/forked.rb

Lines changed: 15 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,24 @@ def initialize(io)
4141
@name = nil
4242
end
4343

44+
def as_json(...)
45+
{
46+
process_id: ::Process.pid,
47+
name: @name,
48+
}
49+
end
50+
51+
def to_json(...)
52+
as_json.to_json(...)
53+
end
54+
4455
# Set the process title to the specified value.
4556
# @parameter value [String] The name of the process.
4657
def name= value
47-
if @name = value
48-
::Process.setproctitle(@name)
49-
end
58+
@name = value
59+
60+
# This sets the process title to an empty string if the name is nil:
61+
::Process.setproctitle(@name.to_s)
5062
end
5163

5264
# The name of the process.

lib/async/container/threaded.rb

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -53,12 +53,23 @@ def self.for(thread)
5353
end
5454

5555
def initialize(io)
56-
@name = nil
5756
@thread = ::Thread.current
5857

5958
super
6059
end
6160

61+
def as_json(...)
62+
{
63+
process_id: ::Process.pid,
64+
thread_id: @thread.object_id,
65+
name: @thread.name,
66+
}
67+
end
68+
69+
def to_json(...)
70+
as_json.to_json(...)
71+
end
72+
6273
# Set the name of the thread.
6374
# @parameter value [String] The name to set.
6475
def name= value

0 commit comments

Comments
 (0)