mirror of
https://github.com/meineerde/rackstash.git
synced 2025-10-17 14:01:01 +00:00
Add Rackstash::Fields::Hash#key? predicate
This commit is contained in:
parent
e13efe5ed3
commit
4a185096d6
@ -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
|
||||
|
||||
@ -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'
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user