Commit 8695997e authored by parker's avatar parker

Google::Protobuf::Struct can access a missing key (#3846)

parent bcda919c
...@@ -149,6 +149,8 @@ module Google ...@@ -149,6 +149,8 @@ module Google
Struct.class_eval do Struct.class_eval do
def [](key) def [](key)
self.fields[key].to_ruby self.fields[key].to_ruby
rescue NoMethodError
nil
end end
def []=(key, value) def []=(key, value)
...@@ -170,6 +172,10 @@ module Google ...@@ -170,6 +172,10 @@ module Google
hash.each { |key, val| ret[key] = val } hash.each { |key, val| ret[key] = val }
ret ret
end end
def has_key?(key)
self.fields.has_key?(key)
end
end end
ListValue.class_eval do ListValue.class_eval do
......
...@@ -60,6 +60,9 @@ class TestWellKnownTypes < Test::Unit::TestCase ...@@ -60,6 +60,9 @@ class TestWellKnownTypes < Test::Unit::TestCase
assert_equal(Google::Protobuf::ListValue.from_a(sublist), assert_equal(Google::Protobuf::ListValue.from_a(sublist),
struct["sublist"]) struct["sublist"])
assert_equal true, struct.has_key?("null")
assert_equal false, struct.has_key?("missing_key")
should_equal = { should_equal = {
"number" => 12345, "number" => 12345,
"boolean-true" => true, "boolean-true" => true,
...@@ -82,6 +85,9 @@ class TestWellKnownTypes < Test::Unit::TestCase ...@@ -82,6 +85,9 @@ class TestWellKnownTypes < Test::Unit::TestCase
# to_h returns a fully-flattened Ruby structure (Hash and Array). # to_h returns a fully-flattened Ruby structure (Hash and Array).
assert_equal(should_equal, struct.to_h) 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. # Test that we can assign Struct and ListValue directly.
struct["substruct"] = Google::Protobuf::Struct.from_hash(substruct) struct["substruct"] = Google::Protobuf::Struct.from_hash(substruct)
struct["sublist"] = Google::Protobuf::ListValue.from_a(sublist) struct["sublist"] = Google::Protobuf::ListValue.from_a(sublist)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment