Skip to content

Commit

Permalink
Implement collection caching
Browse files Browse the repository at this point in the history
  • Loading branch information
sferik committed Jul 25, 2013
1 parent 6c5c431 commit 7d8b272
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 5 deletions.
12 changes: 7 additions & 5 deletions lib/twitter/cursor.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,18 +37,20 @@ def initialize(attrs, key, klass, client, request_method, path, options)
@request_method = request_method.to_sym
@path = path
@options = options
@collection = []
set_attrs(attrs)
end

# @return [Enumerator]
def each(&block)
def each(start = 0, &block)
return to_enum(:each) unless block_given?
@page.each do |element|
Array(@collection[start..-1]).each do |element|
yield element
end
unless last?
start = [@collection.size, start].max
fetch_next_page
each(&block)
each(start, &block)
end
self
end
Expand Down Expand Up @@ -82,8 +84,8 @@ def fetch_next_page

def set_attrs(attrs)
@attrs = attrs
@page = Array(attrs[@key]).map do |element|
@klass ? @klass.new(element) : element
Array(attrs[@key]).each do |element|
@collection << (@klass ? @klass.new(element) : element)
end
end

Expand Down
7 changes: 7 additions & 0 deletions spec/twitter/cursor_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@
@client.follower_ids("sferik").each{count += 1}
expect(count).to eq 6
end
context "with start" do
it "iterates" do
count = 0
@client.follower_ids("sferik").each(5){count += 1}
expect(count).to eq 1
end
end
end

describe "#first?" do
Expand Down

0 comments on commit 7d8b272

Please sign in to comment.