Sha256: fed93400338a6d58af24f5be6cba8b0ffda5b81f87368445a62eab436b1d3dce

Contents?: true

Size: 970 Bytes

Versions: 8

Compression:

Stored size: 970 Bytes

Contents

require 'link_header'

module Footrest
  class Pagination < Faraday::Response::Middleware
    Links = Struct.new(:first, :prev, :current, :next, :last) do
      alias_method :previous, :prev
      alias_method :prevous=, :prev=

      def last_page?
        return false unless self.current && self.last
        self.current == self.last
      end
    end

    def on_complete(response)
      if response[:response_headers]
        if link_header = response[:response_headers][:link]
          links = Links.new
          %w(prev next first last current).each do |page|
            link = find_link(link_header, page)
            response["#{page}_page".to_sym] = link
            links.public_send("#{ page }=", link)
          end
          response[:pagination_links] = links
        end
      end
    end

    def find_link(header, rel)
      link = ::LinkHeader.parse(header).links.find{ |link| link['rel'] == rel }
      link.to_a.first if link
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
footrest-0.5.8 lib/footrest/pagination.rb
footrest-0.5.7 lib/footrest/pagination.rb
footrest-0.5.6 lib/footrest/pagination.rb
footrest-0.5.5 lib/footrest/pagination.rb
footrest-0.5.3 lib/footrest/pagination.rb
footrest-0.5.2 lib/footrest/pagination.rb
footrest-0.5.1 lib/footrest/pagination.rb
footrest-0.5.0 lib/footrest/pagination.rb