From 7580dfe3d1fa8e6962b7f1678f1523a7178f06e4 Mon Sep 17 00:00:00 2001 From: Alex Coomans Date: Wed, 28 Aug 2019 11:01:55 -0500 Subject: [PATCH] Alias #eql? to #== and define #hash on Protobuf::Message --- lib/protobuf/message.rb | 5 ++++ spec/lib/protobuf/message_spec.rb | 46 +++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/lib/protobuf/message.rb b/lib/protobuf/message.rb index a13c0d19..76ddfabb 100644 --- a/lib/protobuf/message.rb +++ b/lib/protobuf/message.rb @@ -173,6 +173,7 @@ def ==(other) end true end + alias :eql? == def [](name) field = _protobuf_message_field[name] @@ -196,6 +197,10 @@ def set_field(name, value, ignore_nil_for_repeated, field = nil) end end + def hash + to_hash.hash + end + ## # Instance Aliases # diff --git a/spec/lib/protobuf/message_spec.rb b/spec/lib/protobuf/message_spec.rb index 96668b67..338644b3 100644 --- a/spec/lib/protobuf/message_spec.rb +++ b/spec/lib/protobuf/message_spec.rb @@ -911,4 +911,50 @@ class MapEntry < ::Protobuf::Message end end end + + describe 'equality & hash codes' do + let(:m1) { ::Test::Resource.new(:name => "Jim") } + let(:m2) { ::Test::Resource.new(:date_created => nil, :name => "Jim") } + let(:m3) { ::Test::Resource.new(:date_created => 55, :name => "Jim") } + + let(:hash) do + { m1 => 4, m3 => 6 } + end + + it 'works with equality' do + expect(m1.nil?).to eq(false) + expect(m1 == 5).to eq(false) + + expect(m1.equal?(m2)).to eq(false) + expect(m1.equal?(m3)).to eq(false) + expect(m2.equal?(m1)).to eq(false) + expect(m2.equal?(m3)).to eq(false) + expect(m3.equal?(m1)).to eq(false) + expect(m3.equal?(m2)).to eq(false) + + expect(m1 == m2).to eq(true) + expect(m2 == m1).to eq(true) + expect(m1.eql?(m2)).to eq(true) + expect(m2.eql?(m1)).to eq(true) + + expect(m1 == m3).to eq(false) + expect(m2 == m3).to eq(false) + expect(m3 == m1).to eq(false) + expect(m3 == m2).to eq(false) + end + + it 'works with hash codes' do + expect(m1.hash).to eq(m2.hash) + expect(m1.hash).to_not eq(m3.hash) + + expect([m1] == [m2]).to eq(true) + expect([m1] - [m2]).to eq([]) + + expect([m1, m3] - [m2]).to eq([m3]) + + expect(hash[m1]).to eq(4) + expect(hash[m2]).to eq(4) + expect(hash[m3]).to eq(6) + end + end end