Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions lib/ostruct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -221,8 +221,14 @@ def marshal_dump # :nodoc:
#
def new_ostruct_member!(name) # :nodoc:
unless @table.key?(name) || is_method_protected!(name)
define_singleton_method!(name) { @table[name] }
define_singleton_method!("#{name}=") {|x| @table[name] = x}
getter_proc = Proc.new { @table[name] }
setter_proc = Proc.new {|x| @table[name] = x}
if defined?(::Ractor)
::Ractor.make_shareable(getter_proc)
::Ractor.make_shareable(setter_proc)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I was thinking this would have the side effect of freezing the OpenStruct instance and @table but actually it does not, which is a CRuby bug: https://bugs.ruby-lang.org/issues/18243
A Ractor should never be able to mutate objects of another Ractor directly of course.

end
define_singleton_method!(name, &getter_proc)
define_singleton_method!("#{name}=", &setter_proc)
end
end
private :new_ostruct_member!
Expand Down
12 changes: 12 additions & 0 deletions test/ostruct/test_ostruct.rb
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,18 @@ def test_ractor
RUBY
end if defined?(Ractor)

def test_access_methods_from_different_ractor
assert_ractor(<<~RUBY, require: 'ostruct')
os = OpenStruct.new
os.value = 100
r = Ractor.new(os) do |x|
v = x.value
Ractor.yield v
end
assert 100 == r.take
RUBY
end if defined?(Ractor)

def test_legacy_yaml
s = "--- !ruby/object:OpenStruct\ntable:\n :foo: 42\n"
o = YAML.safe_load(s, permitted_classes: [Symbol, OpenStruct])
Expand Down