diff --git a/lib/rackstash/fields/hash.rb b/lib/rackstash/fields/hash.rb index cde69ab..f487d60 100644 --- a/lib/rackstash/fields/hash.rb +++ b/lib/rackstash/fields/hash.rb @@ -76,6 +76,24 @@ module Rackstash @raw.empty? end + # Returns true if the given key is present in `self`. + # + # h = Rackstash::Fields::Hash.new + # h.merge!({ "a" => 100, "b" => 200 }) + # + # h.key?("a") #=> true + # h.key?("z") #=> false + # + # @param key [#to_s] the field name. The key will be converted to an + # UTF-8 string before being checked. + # @return [Boolean] `true` if the normalized key is present in `self` + def key?(key) + @raw.key? utf8_encode(key) + end + alias has_key? key? + alias include? key? + alias member? key? + # @return [::Array] a new array populated with the keys from this hash. # @see #values def keys diff --git a/spec/rackstash/fields/hash_spec.rb b/spec/rackstash/fields/hash_spec.rb index 270f106..bc12189 100644 --- a/spec/rackstash/fields/hash_spec.rb +++ b/spec/rackstash/fields/hash_spec.rb @@ -179,6 +179,45 @@ describe Rackstash::Fields::Hash do end end + describe '#key?' do + it 'checks whether a key was set' do + hash['hello'] = 'World' + expect(hash.key?('hello')).to be true + expect(hash.key?('Hello')).to be false + expect(hash.key?('goodbye')).to be false + end + + it 'checks keys with stringified names' do + hash['hello'] = 'World' + expect(hash.key?('hello')).to be true + expect(hash.key?(:hello)).to be true + end + + it 'can use the alias #has_key?' do + hash['hello'] = 'World' + expect(hash.has_key?('hello')).to be true + expect(hash.has_key?('goodbye')).to be false + + # We can also use the rspec matcher + expect(hash).to have_key 'hello' + end + + it 'can use the alias #include?' do + hash['hello'] = 'World' + expect(hash.include?('hello')).to be true + expect(hash.include?('goodbye')).to be false + + # We can also use the rspec matcher + expect(hash).to include 'hello' + end + + it 'can use the alias #member?' do + hash['hello'] = 'World' + expect(hash.member?('hello')).to be true + expect(hash.member?('goodbye')).to be false + end + end + describe '#keys' do it 'returns an array of keys' do hash['foo'] = 'bar'