Skip to content

Commit

Permalink
Merge pull request #586 from lucasallan/map_each
Browse files Browse the repository at this point in the history
Add each as an alias for each_pair for Concurrent::Map
  • Loading branch information
Petr Chalupa committed Oct 16, 2016
2 parents 3894d5b + d83fb11 commit d894aa6
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 40 deletions.
2 changes: 2 additions & 0 deletions lib/concurrent/map.rb
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,8 @@ def each_value
each_pair {|k, v| yield v}
end unless method_defined?(:each_value)

alias_method :each, :each_pair unless method_defined?(:each)

def key(value)
each_pair {|k, v| return k if v == value}
nil
Expand Down
46 changes: 46 additions & 0 deletions spec/concurrent/collection_each_shared.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
shared_examples :collection_each do

it 'common' do
@cache.send(method) { |k, v| fail }
expect(@cache).to eq @cache.send(method) {}
@cache[:a] = 1

h = {}
@cache.send(method) { |k, v| h[k] = v }
expect({:a => 1}).to eq h

@cache[:b] = 2
h = {}
@cache.send(method) { |k, v| h[k] = v }
expect({:a => 1, :b => 2}).to eq h
end

it 'pair iterator' do
@cache[:a] = 1
@cache[:b] = 2
i = 0
r = @cache.send(method) do |k, v|
if i == 0
i += 1
next
fail
elsif i == 1
break :breaked
end
end

expect(:breaked).to eq r
end

it 'allows modification' do
@cache[:a] = 1
@cache[:b] = 1
@cache[:c] = 1

expect_size_change(1) do
@cache.send(method) do |k, v|
@cache[:z] = 1
end
end
end
end
47 changes: 7 additions & 40 deletions spec/concurrent/map_spec.rb
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
require_relative 'collection_each_shared'
Thread.abort_on_exception = true

module Concurrent
Expand Down Expand Up @@ -623,48 +624,14 @@ def key # assert_collision_resistance expects to be able to call .key to get the
end

describe '#each_pair' do
it 'common' do
@cache.each_pair { |k, v| fail }
expect(@cache).to eq @cache.each_pair {}
@cache[:a] = 1

h = {}
@cache.each_pair { |k, v| h[k] = v }
expect({:a => 1}).to eq h

@cache[:b] = 2
h = {}
@cache.each_pair { |k, v| h[k] = v }
expect({:a => 1, :b => 2}).to eq h
end

it 'pair iterator' do
@cache[:a] = 1
@cache[:b] = 2
i = 0
r = @cache.each_pair do |k, v|
if i == 0
i += 1
next
fail
elsif i == 1
break :breaked
end
end

expect(:breaked).to eq r
it_should_behave_like :collection_each do
let(:method) { :each_pair }
end
end

it 'allows modification' do
@cache[:a] = 1
@cache[:b] = 1
@cache[:c] = 1

expect_size_change(1) do
@cache.each_pair do |k, v|
@cache[:z] = 1
end
end
describe '#each' do
it_should_behave_like :collection_each do
let(:method) { :each }
end
end

Expand Down

0 comments on commit d894aa6

Please sign in to comment.