Skip to content

Commit 485d419

Browse files
committed
Fix enum equality
1 parent b16196e commit 485d419

2 files changed

Lines changed: 28 additions & 0 deletions

File tree

lib/protobuf/enum.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,20 @@ def initialize(parent_class, name, tag)
259259
super(tag)
260260
end
261261

262+
# Custom equality method since otherwise identical values from different
263+
# enums will be considered equal by Integer's equality method (or
264+
# Fixnum's on Ruby < 2.4.0).
265+
#
266+
def ==(other)
267+
if other.is_a?(Protobuf::Enum)
268+
parent_class == other.parent_class && tag == other.tag
269+
elsif tag.class == other.class
270+
tag == other
271+
else
272+
false
273+
end
274+
end
275+
262276
# Overriding the class so ActiveRecord/Arel visitor will visit the enum as an
263277
# Integer.
264278
#

spec/lib/protobuf/enum_spec.rb

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,20 @@
2121
end
2222
end
2323

24+
describe '.==' do
25+
it 'is true for identical values' do
26+
expect(Test::EnumTestType::THREE).to eq(Test::EnumTestType::THREE)
27+
end
28+
29+
it 'is false for different values in the same enum' do
30+
expect(Test::EnumTestType::TWO).to_not eq(Test::EnumTestType::THREE)
31+
end
32+
33+
it 'is false for values from different enums' do
34+
expect(Test::EnumTestType::THREE).to_not eq(Test::AliasedEnum::THREE)
35+
end
36+
end
37+
2438
describe '.aliases_allowed?' do
2539
it 'is false when the option is not set' do
2640
expect(Test::EnumTestType.aliases_allowed?).to be false

0 commit comments

Comments
 (0)