billionsend 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,39 @@
1
+ # frozen_string_literal: true
2
+
3
+ module BillionSend
4
+ # Iterates over every item of a cursor-paginated list.
5
+ #
6
+ # Lists are newest first: +after+ takes the last id of a page and pages
7
+ # toward older items, +before+ takes the first id and pages toward newer ones.
8
+ #
9
+ # A page without a data array raises {Error} ("application_error", no status)
10
+ # at once; a page that has more but whose item to continue from has no id
11
+ # hands out its items first, then raises.
12
+ module Pagination
13
+ # An Enumerator over every item, calling +fetch.call(after, before)+ for each
14
+ # page (a Hash with "data" and "has_more").
15
+ def self.each_item(after:, before:, &fetch)
16
+ Enumerator.new do |out|
17
+ backward = !before.nil? && after.nil?
18
+ loop do
19
+ page = fetch.call(after, before)
20
+ items = page.is_a?(Hash) ? page["data"] : nil
21
+ raise Error, "The list page has no data array" unless items.is_a?(Array)
22
+
23
+ items.each { |item| out << item }
24
+ break if page["has_more"] != true || items.empty?
25
+
26
+ cursor = backward ? items.first : items.last
27
+ id = cursor.is_a?(Hash) ? cursor["id"] : nil
28
+ raise Error, "The last item of the list page has no id to continue from" unless id.is_a?(String) && !id.empty?
29
+
30
+ if backward
31
+ before = id
32
+ else
33
+ after = id
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
39
+ end