diff options
author | Joshua Haberman <jhaberman@gmail.com> | 2018-07-02 13:56:25 -0700 |
---|---|---|
committer | GitHub <noreply@github.com> | 2018-07-02 13:56:25 -0700 |
commit | e00266a74ee0eb95cc745fdf4f346b28d2018332 (patch) | |
tree | c24396cede56430c6bcf6a43b165f94893c7041f | |
parent | e0579ac645df504dd80163e00bce997f470cc5ab (diff) | |
parent | 8695997eb5adb3c504c3615f0e6f3891a9b7ebde (diff) |
Merge pull request #3847 from FX-HAO/master
Google::Protobuf::Struct can access a missing key (#3846)
-rw-r--r-- | ruby/lib/google/protobuf/well_known_types.rb | 6 | ||||
-rw-r--r-- | ruby/tests/well_known_types_test.rb | 6 |
2 files changed, 12 insertions, 0 deletions
diff --git a/ruby/lib/google/protobuf/well_known_types.rb b/ruby/lib/google/protobuf/well_known_types.rb index 3e759591..2ee65bc2 100644 --- a/ruby/lib/google/protobuf/well_known_types.rb +++ b/ruby/lib/google/protobuf/well_known_types.rb @@ -155,6 +155,8 @@ module Google Struct.class_eval do def [](key) self.fields[key].to_ruby + rescue NoMethodError + nil end def []=(key, value) @@ -176,6 +178,10 @@ module Google hash.each { |key, val| ret[key] = val } ret end + + def has_key?(key) + self.fields.has_key?(key) + end end ListValue.class_eval do diff --git a/ruby/tests/well_known_types_test.rb b/ruby/tests/well_known_types_test.rb index 240281e7..f35f7b13 100644 --- a/ruby/tests/well_known_types_test.rb +++ b/ruby/tests/well_known_types_test.rb @@ -60,6 +60,9 @@ class TestWellKnownTypes < Test::Unit::TestCase assert_equal(Google::Protobuf::ListValue.from_a(sublist), struct["sublist"]) + assert_equal true, struct.has_key?("null") + assert_equal false, struct.has_key?("missing_key") + should_equal = { "number" => 12345, "boolean-true" => true, @@ -82,6 +85,9 @@ class TestWellKnownTypes < Test::Unit::TestCase # to_h returns a fully-flattened Ruby structure (Hash and Array). assert_equal(should_equal, struct.to_h) + # Test that we can safely access a missing key + assert_equal(nil, struct["missing_key"]) + # Test that we can assign Struct and ListValue directly. struct["substruct"] = Google::Protobuf::Struct.from_hash(substruct) struct["sublist"] = Google::Protobuf::ListValue.from_a(sublist) |