Skip to content

Commit 5596f6d

Browse files
y-yagicopybara-github
authored andcommitted
[Ruby]Implement #to_hash for message classes (#20866)
In Ruby, `#to_hash` is used for implicit conversion. https://bugs.ruby-lang.org/issues/10180 For example, Active Support uses `#to_hash` when converting an object to JSON. https://github.com/rails/rails/blob/621aa49cefce3313fbc672e2f3681103da686a0e/activesupport/lib/active_support/core_ext/object/json.rb#L60 This PR adds `#to_hash` as the alias of `#to_h`. This allows message objects to convert implicitly to other formats correctly. Fixes #17037 Closes #20866 COPYBARA_INTEGRATE_REVIEW=#20866 from y-yagi:fixes_17037 e0422bb PiperOrigin-RevId: 741713385
1 parent aaa3f52 commit 5596f6d

File tree

2 files changed

+14
-0
lines changed

2 files changed

+14
-0
lines changed

ruby/lib/google/protobuf/message_exts.rb

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,10 @@ def to_proto(options = {})
2525
self.class.encode(self, options)
2626
end
2727

28+
def to_hash
29+
self.to_h
30+
end
31+
2832
end
2933
class AbstractMessage
3034
include MessageExts

ruby/tests/basic.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -496,6 +496,16 @@ def test_to_h
496496
assert_equal expected_result, m.to_h
497497
end
498498

499+
def test_to_hash
500+
m = TestMessage.new(
501+
:optional_bool => true,
502+
:optional_double => -10.100001,
503+
:optional_string => 'foo',
504+
:repeated_string => ['bar1', 'bar2'],
505+
:repeated_msg => [TestMessage2.new(:foo => 100)]
506+
)
507+
assert_equal m.to_hash, m.to_h
508+
end
499509

500510
def test_json_maps
501511
m = MapMessage.new(:map_string_int32 => {"a" => 1})

0 commit comments

Comments
 (0)