2015-12-31 18:33:35 -05:00
|
|
|
# frozen_string_literal: true
|
2019-04-01 12:20:41 -04:00
|
|
|
|
2012-07-18 01:14:15 -04:00
|
|
|
module Sidekiq
|
|
|
|
module Paginator
|
2019-04-01 12:20:41 -04:00
|
|
|
def page(key, pageidx = 1, page_size = 25, opts = nil)
|
2012-07-18 01:14:15 -04:00
|
|
|
current_page = pageidx.to_i < 1 ? 1 : pageidx.to_i
|
|
|
|
pageidx = current_page - 1
|
|
|
|
total_size = 0
|
|
|
|
items = []
|
|
|
|
starting = pageidx * page_size
|
|
|
|
ending = starting + page_size - 1
|
|
|
|
|
|
|
|
Sidekiq.redis do |conn|
|
|
|
|
type = conn.type(key)
|
2019-09-07 17:49:28 -04:00
|
|
|
rev = opts && opts[:reverse]
|
2012-07-18 01:14:15 -04:00
|
|
|
|
|
|
|
case type
|
2019-04-01 12:20:41 -04:00
|
|
|
when "zset"
|
|
|
|
total_size, items = conn.multi {
|
2014-02-01 16:51:09 -05:00
|
|
|
conn.zcard(key)
|
|
|
|
if rev
|
2019-04-01 12:20:41 -04:00
|
|
|
conn.zrevrange(key, starting, ending, with_scores: true)
|
2014-02-01 16:51:09 -05:00
|
|
|
else
|
2019-04-01 12:20:41 -04:00
|
|
|
conn.zrange(key, starting, ending, with_scores: true)
|
2014-02-01 16:51:09 -05:00
|
|
|
end
|
2019-04-01 12:20:41 -04:00
|
|
|
}
|
2015-04-10 17:28:28 -04:00
|
|
|
[current_page, total_size, items]
|
2019-04-01 12:20:41 -04:00
|
|
|
when "list"
|
|
|
|
total_size, items = conn.multi {
|
2014-02-01 16:51:09 -05:00
|
|
|
conn.llen(key)
|
2019-09-07 17:49:28 -04:00
|
|
|
if rev
|
|
|
|
conn.lrange(key, -ending - 1, -starting - 1)
|
|
|
|
else
|
|
|
|
conn.lrange(key, starting, ending)
|
|
|
|
end
|
2019-04-01 12:20:41 -04:00
|
|
|
}
|
2019-09-07 17:49:28 -04:00
|
|
|
items.reverse! if rev
|
2015-04-10 17:28:28 -04:00
|
|
|
[current_page, total_size, items]
|
2019-04-01 12:20:41 -04:00
|
|
|
when "none"
|
2015-04-10 17:28:28 -04:00
|
|
|
[1, 0, []]
|
2012-07-18 01:14:15 -04:00
|
|
|
else
|
|
|
|
raise "can't page a #{type}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|