-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathfeed.rb
50 lines (41 loc) · 1.16 KB
/
feed.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
require 'bundler'
Bundler.setup(:default, :development)
require 'mongoid-scroll'
require 'faker'
Mongoid.logger.level = Logger::INFO
Mongoid.connect_to 'mongoid_scroll_demo'
Mongoid.purge!
module Feed
class Item
include Mongoid::Document
field :title, type: String
field :position, type: Integer
index(position: 1, _id: 1)
end
end
# total items to insert
total_items = 20
# a MongoDB query will be executed every scroll_by items
scroll_by = 7
# insert items with a position out-of-order
rands = (0..total_items).to_a.sort { |_l, _r| rand }[0..total_items]
total_items.times do |_i|
Feed::Item.create! title: Faker::Lorem.sentence, position: rands.pop
end
Feed::Item.create_indexes
total_shown = 0
next_cursor = nil
loop do
current_cursor = next_cursor
next_cursor = nil
Feed::Item.asc(:position).limit(scroll_by).scroll(current_cursor) do |item, cursor|
puts "#{item.position}: #{item.title}"
next_cursor = cursor.next_cursor
total_shown += 1
end
break unless next_cursor
# destroy an item just for the heck of it, scroll is not affected
Feed::Item.asc(:position).first.destroy
end
# this will be 20
puts "Shown #{total_shown} items."