Ver código fonte

Add Google::Protobuf::Any.pack convenience class method. (#4719)

igorpeshansky 7 anos atrás
pai
commit
944693c44c

+ 6 - 0
ruby/lib/google/protobuf/well_known_types.rb

@@ -39,6 +39,12 @@ module Google
   module Protobuf
 
     Any.class_eval do
+      def self.pack(msg, type_url_prefix='type.googleapis.com/')
+        any = self.new
+        any.pack(msg, type_url_prefix)
+        any
+      end
+
       def pack(msg, type_url_prefix='type.googleapis.com/')
         if type_url_prefix.empty? or type_url_prefix[-1] != '/' then
           self.type_url = "#{type_url_prefix}/#{msg.class.descriptor.name}"

+ 7 - 1
ruby/tests/well_known_types_test.rb

@@ -120,11 +120,17 @@ class TestWellKnownTypes < Test::Unit::TestCase
   end
 
   def test_any
-    any = Google::Protobuf::Any.new
     ts = Google::Protobuf::Timestamp.new(seconds: 12345, nanos: 6789)
+
+    any = Google::Protobuf::Any.new
     any.pack(ts)
 
     assert any.is(Google::Protobuf::Timestamp)
     assert_equal ts, any.unpack(Google::Protobuf::Timestamp)
+
+    any = Google::Protobuf::Any.pack(ts)
+
+    assert any.is(Google::Protobuf::Timestamp)
+    assert_equal ts, any.unpack(Google::Protobuf::Timestamp)
   end
 end