Skip to content

Commit

Permalink
Allow properties to be accessed even when the object is moved to anot…
Browse files Browse the repository at this point in the history
…her Ractor (#29)
  • Loading branch information
rm155 committed Aug 20, 2021
1 parent 8534f69 commit d85639f
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
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)
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

0 comments on commit d85639f

Please sign in to comment.