Skip to content

Commit fc8fb74

Browse files
authored
fix(gapic-common): Fixed handling of optional fields in coerce (#954)
1 parent 095c530 commit fc8fb74

File tree

2 files changed

+10
-0
lines changed

2 files changed

+10
-0
lines changed

gapic-common/lib/gapic/protobuf.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ module Protobuf
3131
# @return [Object] An instance of the given message class.
3232
def self.coerce hash, to:
3333
return hash if hash.is_a? to
34+
return nil if hash.nil?
3435

3536
# Special case handling of certain types
3637
return time_to_timestamp hash if to == Google::Protobuf::Timestamp && hash.is_a?(Time)

gapic-common/test/gapic/protobuf/coerce_test.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,15 @@ class ProtobufCoerceTest < Minitest::Spec
3535
_(user.type).must_equal USER_TYPE
3636
end
3737

38+
it "handles optional fields in a simple hash" do
39+
hash = { name: USER_NAME, type: USER_TYPE, timestamp: nil }
40+
user = Gapic::Protobuf.coerce hash, to: Gapic::Examples::User
41+
_(user).must_be_kind_of Gapic::Examples::User
42+
_(user.name).must_equal USER_NAME
43+
_(user.type).must_equal USER_TYPE
44+
_(user.timestamp).must_be_nil
45+
end
46+
3847
it "creates a protobuf message from a hash with a nested message" do
3948
request_hash = { name: REQUEST_NAME, user: Gapic::Examples::User.new(name: USER_NAME, type: USER_TYPE) }
4049
request = Gapic::Protobuf.coerce request_hash, to: Gapic::Examples::Request

0 commit comments

Comments
 (0)