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

Paginated requests Enumerator #10

Open
arturictus opened this issue May 30, 2019 · 0 comments
Open

Paginated requests Enumerator #10

arturictus opened this issue May 30, 2019 · 0 comments
Labels

Comments

@arturictus
Copy link
Owner

Example of code using pagination as enumerator

 def self.paginated_get(path, options = {})
      Enumerator.new do |y|
        params  = options.dup
        page    = nil
        total   = 0
        size    = params.delete(:size) { 50 }

        loop do
          response = get(path, { page: page, size: size }.merge(params))
          data = JSON.parse(response.body)
          objects = data["_embedded"].present? ?
                      data["_embedded"]["intelligenceObjects"] :
                      []
          total += objects.length

          objects.each do |element|
            y.yield element
          end

          break if (data["page"]["number"] >= (data["page"]["totalPages"] - 1) ||
                    objects.empty? ||
                    total >= MAX_OBJECTS)

          page = data["page"]["number"] + 1
        end
      end
    end

usage:

Endpoint.paginated_get(params) do |response|
# do somthing
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant