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

Cache #find_all #1147

Merged
merged 2 commits into from Apr 1, 2017
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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