Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add #select, #reject and #compact methods to Sinatra::IndifferentHash #1711

Merged
merged 1 commit into from
Aug 17, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions lib/sinatra/indifferent_hash.rb
Original file line number Diff line number Diff line change
Expand Up @@ -180,6 +180,20 @@ def transform_keys!
end
end

def select(*args, &block)
return to_enum(:select) unless block_given?
dup.tap { |hash| hash.select!(*args, &block) }
end

def reject(*args, &block)
return to_enum(:reject) unless block_given?
dup.tap { |hash| hash.reject!(*args, &block) }
end

def compact
dup.tap(&:compact!)
end if method_defined?(:compact) # Added in Ruby 2.4

private

def convert_key(key)
Expand Down
53 changes: 53 additions & 0 deletions test/indifferent_hash_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -262,4 +262,57 @@ def test_transform_keys
assert_equal :a, hash2[:A]
assert_equal :a, hash2[?A]
end

def test_select
hash = @hash.select { |k, v| v == :a }
assert_equal Sinatra::IndifferentHash[a: :a], hash
assert_instance_of Sinatra::IndifferentHash, hash

hash2 = @hash.select { |k, v| true }
assert_equal @hash, hash2
assert_instance_of Sinatra::IndifferentHash, hash2

enum = @hash.select
assert_instance_of Enumerator, enum
end

def test_select!
@hash.select! { |k, v| v == :a }
assert_equal Sinatra::IndifferentHash[a: :a], @hash
end

def test_reject
hash = @hash.reject { |k, v| v != :a }
assert_equal Sinatra::IndifferentHash[a: :a], hash
assert_instance_of Sinatra::IndifferentHash, hash

hash2 = @hash.reject { |k, v| false }
assert_equal @hash, hash2
assert_instance_of Sinatra::IndifferentHash, hash2

enum = @hash.reject
assert_instance_of Enumerator, enum
end

def test_reject!
@hash.reject! { |k, v| v != :a }
assert_equal Sinatra::IndifferentHash[a: :a], @hash
end

def test_compact
skip_if_lacking :compact

hash_with_nil_values = @hash.merge({?z => nil})
compacted_hash = hash_with_nil_values.compact
assert_equal @hash, compacted_hash
assert_instance_of Sinatra::IndifferentHash, compacted_hash

empty_hash = Sinatra::IndifferentHash.new
compacted_hash = empty_hash.compact
assert_equal empty_hash, compacted_hash

non_empty_hash = Sinatra::IndifferentHash[a: :a]
compacted_hash = non_empty_hash.compact
assert_equal non_empty_hash, compacted_hash
end
end