1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-12-20 15:21:12 +00:00

Add consistent hash method to Rackstash::Fields::AbstractCollection

This follows the rule that two objects which are eql? also have the same
hash value. It is also required to ensure that we can use collections in
sets, hashes and arrays where the hash-equality is checked for certain
operations.
This commit is contained in:
Holger Just 2017-02-17 19:10:27 +01:00
parent 95fdb38ea8
commit e13efe5ed3
2 changed files with 22 additions and 0 deletions

View File

@ -22,6 +22,16 @@ module Rackstash
end end
alias eql? == alias eql? ==
# Compute a hash-code for this collection.
#
# Two collections with the same raw content will have the same hash code
# (and will compare using {#eql?}).
#
# @return [Integer] the hash ID of `self`
def hash
[self.class, raw].hash
end
# Show a human-readable representation of `self`. To get a machine- # Show a human-readable representation of `self`. To get a machine-
# readable "export" of the contained data, use {#as_json} or one of its # readable "export" of the contained data, use {#as_json} or one of its
# aliases instead. # aliases instead.

View File

@ -91,6 +91,18 @@ describe Rackstash::Fields::AbstractCollection do
end end
end end
describe '#hash' do
it 'returns the same hash for the same raw content' do
collection.send(:raw=, [123, 'foo'])
collection2 = Rackstash::Fields::AbstractCollection.new
collection2.send(:raw=, [123, 'foo'])
expect(collection.send(:raw)).not_to equal collection2.send(:raw)
expect(collection.hash).to eql collection2.hash
end
end
describe '#raw' do describe '#raw' do
it 'is a protected accessor' do it 'is a protected accessor' do
expect { collection.raw = nil }.to raise_error NoMethodError expect { collection.raw = nil }.to raise_error NoMethodError