Skip to content

Commit

Permalink
Merge pull request #1348 from no-reply/fast-each
Browse files Browse the repository at this point in the history
Implement enumeration for `Relation#each`
  • Loading branch information
Thomas Johnson authored Aug 31, 2018
2 parents 4a13ae2 + 4e49a42 commit 534b65c
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 1 deletion.
2 changes: 2 additions & 0 deletions lib/active_fedora/associations/collection_proxy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ def initialize(association)
merge! association.scope(nullify: false)
end

delegate :each, to: :to_a

def target
@association.target
end
Expand Down
10 changes: 10 additions & 0 deletions lib/active_fedora/relation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,16 @@ def scope_for_create
@scope_for_create ||= where_values_hash.merge(create_with_value)
end

def each
if loaded?
@records.each { |item| yield item } if block_given?
@records.to_enum
else
find_each(where_values) { |item| yield item } if block_given?
enum_for(:find_each, where_values)
end
end

private

VALID_FIND_OPTIONS = [:order, :limit, :start, :conditions, :cast].freeze
Expand Down
3 changes: 2 additions & 1 deletion lib/active_fedora/relation/delegation.rb
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@ module Delegation # :nodoc:
:keep_if, :pop, :shift, :delete_at, :select!
].to_set

delegate :length, :collect, :map, :each, :all?, :include?, :to_ary, to: :to_a
delegate :length, :map, :to_ary, to: :to_a
delegate :all?, :blank?, :collect, :include?, :present?, to: :each

protected

Expand Down
34 changes: 34 additions & 0 deletions spec/integration/relation_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,40 @@ class Book < ActiveFedora::Base
expect_any_instance_of(ActiveFedora::Relation).to_not receive :find_each
libraries[0]
end

it "does not reload" do
expect_any_instance_of(ActiveFedora::Relation).to_not receive :find_each
libraries.each { |l| l.id }
end
end

describe '#each' do
before { Book.create }

it 'returns an enumerator' do
expect(libraries.each).to be_a Enumerator
end

it 'yields the items' do
expect { |b| libraries.each(&b) }
.to yield_successive_args(*Library.all.to_a)
end

it 'when called from Base yields all items' do
expect { |b| ActiveFedora::Base.all.each(&b) }
.to yield_successive_args(*(Library.all.to_a + Book.all.to_a))
end

context 'when cached' do
it 'returns an enumerator' do
expect(libraries.each).to be_a Enumerator
end

it 'yields the items' do
expect { |b| libraries.each(&b) }
.to yield_successive_args(*Library.all.to_a)
end
end
end

describe "#find" do
Expand Down

0 comments on commit 534b65c

Please sign in to comment.