Closed Looooong closed 1 year ago
Thanks for the input, is this branched off #174 or an alternative?
This is an alternative.
One more thing, I did copy the test suite from #174.
I also thought of another way to solve the issue with the anonymous class string "#<Class:0x005559d7de5338>"
. This involes using regex to get the object address (0x005559d7de5338
) from this string and converting this address to object ID, which will then be fed to ObjectSpace._id2ref
to get the original anonymous class. Here is an example:
klass = Class.new
klass.to_s # "#<Class:0x005559d7de5338>"
address = klass.to_s.match(/#<Class:0x([0-9a-f]+)>/).captures[0] # 005559d7de5338
ref = ObjectSpace._id2ref(address.to_i(16) >> 1)
ref == klass # true
With this solution, we can avoid calling to_s
completely. What do you think?
With this solution, we can avoid calling
to_s
completely. What do you think?
It's a bit fancy for my tastes (:smile:) and I wonder if it works in JRuby.
I'm not actually convinced we need to support anonymous classes. We do use anonymous classes in the specs but not because we want to support them :thinking:
@lkang @wheeyls any thoughts?
It's a bit fancy for my tastes () and I wonder if it works in JRuby.
I don't work with JRuby so I have no idea.
On another note, ObjectSpace._id2ref
is not safe that it can get any object exists in the memory. Special care should be taken to make sure that we get back a class or a module.
def string_to_anonymous(klass)
match = klass.match(/#<(Class|Module):0x([0-9a-f]+)>/)
return if match.nil?
type = match.captures[0]
address = match.captures[1]
ref = ObjectSpace._id2ref(address.to_i(16) >> 1)
ref.class.name == type ? ref : nil
end
I have tested ObjectSpace._id2ref
alternative and it indeed doesn't work with JRuby, and, concerningly, Ruby HEAD. In this case, I think we have the following options:
allowed_classes
into constantized classes and stringified classes, then compare the classes accordingly. This is my original implementation, but I don't like this one.If we only use anonymous classes in the specs then we can replace anonymous class with a constant one.
Who can make the decision on whether to support anonymous classes? I don't feel like it would be my place to take a test out of the suite.
This PR is a follow-up of #174 and it solves issue with anonymous class string. It doesn't avoid calling
to_s
completely, but only callsto_s
whenallowed_classes
contains a string like#<Class:0xXXXXXX>
.
@krisleech I decided to revert to my original implementation, simplify my code and add a couple of tests. It should be good now. I'm waiting for your review.
In RailsEventStore they only allow anonymous classes with a self.name
method, e.g.
Class.new do
def name
"MyClass"
end
end
Great! I will take a look at it.
This PR is a follow-up of #174 and it solves issue with anonymous class string. It doesn't avoid calling
to_s
completely, but only callsto_s
whenallowed_classes
contains a string like#<Class:0xXXXXXX>
.