diff --git a/lib/rackstash/fields/hash.rb b/lib/rackstash/fields/hash.rb index bdb8d6f..6684104 100644 --- a/lib/rackstash/fields/hash.rb +++ b/lib/rackstash/fields/hash.rb @@ -290,6 +290,12 @@ module Rackstash @raw.keys end + # @return [Integer] the number of key-value pairs in the hash + def length + @raw.length + end + alias size length + # Returns a new {Hash} containing the contents of `hash` and of # `self`. If no block is specified, the value for entries with duplicate # keys will be that of `hash`. Otherwise the value for each duplicate key diff --git a/spec/rackstash/fields/hash_spec.rb b/spec/rackstash/fields/hash_spec.rb index fe01441..deda102 100644 --- a/spec/rackstash/fields/hash_spec.rb +++ b/spec/rackstash/fields/hash_spec.rb @@ -495,6 +495,24 @@ describe Rackstash::Fields::Hash do end end + describe '#length' do + it 'returns the length of the hash' do + expect(hash.length).to eql 0 + + hash['foo'] = 'bar' + expect(hash.length).to eql 1 + + hash.clear + expect(hash.length).to eql 0 + end + + it 'can use size as an alias' do + expect(hash.size).to eql 0 + hash['foo'] = 'bar' + expect(hash.size).to eql 1 + end + end + describe '#merge!' do it 'rejects not hash-convertible arguments' do expect { hash.merge!(nil) }.to raise_error TypeError