Skip to content

Commit

Permalink
Merge pull request #1147 from nanoc/cache-find-all
Browse files Browse the repository at this point in the history
Cache #find_all
  • Loading branch information
denisdefreyne committed Apr 1, 2017
2 parents dfdc830 + 9e33620 commit 8b107d5
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 2 deletions.
21 changes: 21 additions & 0 deletions lib/nanoc/base/entities/identifiable_collection.rb
Expand Up @@ -37,6 +37,15 @@ def [](arg)
end
end

contract C::Any => C::IterOf[C::RespondTo[:identifier]]
def find_all(arg)
if frozen?
find_all_memoized(arg)
else
find_all_unmemoized(arg)
end
end

contract C::None => C::ArrayOf[C::RespondTo[:identifier]]
def to_a
@objects.to_a
Expand Down Expand Up @@ -77,6 +86,18 @@ def get_memoized(arg)
end
memoize :get_memoized

contract C::Any => C::IterOf[C::RespondTo[:identifier]]
def find_all_unmemoized(arg)
pat = Nanoc::Int::Pattern.from(arg)
select { |i| pat.match?(i.identifier) }
end

contract C::Any => C::IterOf[C::RespondTo[:identifier]]
def find_all_memoized(arg)
find_all_unmemoized(arg)
end
memoize :find_all_memoized

def object_with_identifier(identifier)
if frozen?
@mapping[identifier.to_s]
Expand Down
3 changes: 1 addition & 2 deletions lib/nanoc/base/views/identifiable_collection_view.rb
Expand Up @@ -43,8 +43,7 @@ def size
#
# @return [Enumerable]
def find_all(arg)
pat = Nanoc::Int::Pattern.from(arg)
select { |i| pat.match?(i.identifier) }
@objects.find_all(arg).map { |i| view_class.new(i, @context) }
end

# @overload [](string)
Expand Down
34 changes: 34 additions & 0 deletions spec/nanoc/base/entities/identifiable_collection_spec.rb
Expand Up @@ -9,4 +9,38 @@

it { is_expected.to be_a(described_class) }
end

describe '#find_all' do
let(:objects) do
[
double(:identifiable, identifier: Nanoc::Identifier.new('/about.css')),
double(:identifiable, identifier: Nanoc::Identifier.new('/about.md')),
double(:identifiable, identifier: Nanoc::Identifier.new('/style.css')),
]
end

let(:arg) { raise 'override me' }

subject { identifiable_collection.find_all(arg) }

context 'with string' do
let(:arg) { '/*.css' }

it 'contains objects' do
expect(subject.size).to eql(2)
expect(subject.find { |iv| iv.identifier == '/about.css' }).to eq(objects[0])
expect(subject.find { |iv| iv.identifier == '/style.css' }).to eq(objects[2])
end
end

context 'with regex' do
let(:arg) { %r{\.css\z} }

it 'contains objects' do
expect(subject.size).to eql(2)
expect(subject.find { |iv| iv.identifier == '/about.css' }).to eq(objects[0])
expect(subject.find { |iv| iv.identifier == '/style.css' }).to eq(objects[2])
end
end
end
end

0 comments on commit 8b107d5

Please sign in to comment.