Ruby question: how to unpack Any instance without wrapped class?
The Ruby Any type encodes the wrapped message class as a type_url:
> ts = Google::Protobuf::Timestamp.new :nanos => 123
> a = Google::Protobuf::Any.new.pack ts
> puts a.inspect
<Google::Protobuf::Any: type_url: "type.googleapis.com/google.protobuf.Timestamp", value: "\x10{">
However, to unpack the Any type, you need to specify the wrapped class:
a.unpack Google::Protobuf::Timestamp
If I don't know that the wrapped class is Google::Protobuf::Timestamp, it seems that the protobuf library should be able to infer the right argument from the type_url. But if it can't, does the protobuf runtime keep a registry of messages and type URLs so that the calling code can do the conversion?
> a.unpack Google::Protobuf::RuntimeRegistry.lookup(a.type_url)
?
cc: @haberman
https://github.com/google/protobuf/blob/master/ruby/ext/google/protobuf_c/defs.c#L199 It seems you can find a descriptor via its name from DescriptorPool
Yes, more specifically the code would be:
type = Google::Protobuf::DescriptorPool.generated_pool.lookup(name)
We don't have any code built-in for converting type URL to name yet.
Hi Guys, I need some help regarding unpacking the Google::Protobuf::Any type I'm getting below error when unpacking object of type Google::Protobuf::Any to a specific type defined in my code
undefined method `unpack` for #<Google::Protobuf::Any:0x007fae4e97e8d0> (NoMethodError)
Let's say abc is the object
when I abc.inspect, it gives me below output
<Google::Protobuf::Any: type_url: "type.googleapis.com/protocol.MyType", value: "\n\x15A_m">
But when I try to run abc.unpack protocol::MyType, I get the error mentioned above.
Is there anything wrong I am doing? Any help is much appreciated. Thank you.
It got solved. I had to require google/protobuf/well_known_types
It got solved. I had to require
google/protobuf/well_known_types
could you post the ruby fragment?
Thanks Olindo
@pindaroli A year later, I'm coming across this issue and your comment (a year later!).
I suspect you've figured out the answer now, but posting here for future travelers:
The protobuf Ruby gem does not require the well_known_types.rb file (source file here), so if you want to take advantage of any of the methods it adds (e.g. to_time on Timestamp class instances), you'll have to require it manually in your application:
# In Gemfile or similar…
require 'google/protobuf'
require 'google/protobuf/well_known_types`
I only came to that while reading through #6360 and noticed the file being manually required in the example code. It seems someone attempted to ask why this particular file (and only this particular file…) isn't required in the gem (see #3807), but the issue was closed.