Sha256: cadd24b7938c2c3ad7ba7078260e731452ab510bf9c21773e3466ff88a96a483

Contents?: true

Size: 1.77 KB

Versions: 1

Compression:

Stored size: 1.77 KB

Contents

require 'cgi'
require_relative 'hal_resource'

module Finix
  class Pagination

    include Enumerable
    include HalResource

    attr_accessor :resource_class

    def initialize(href, opts={})
      @hyperlinks = {}
      @attributes = {}

      @hyperlinks[:self] = href
      @resource_class = nil
    end

    def each
      return enum_for :each unless block_given?
      current
      loop do
        items.each { |item| yield item }
        fetch :next
      end
    end

    def current
      refresh unless items
      items
    end

    def fetch(scope) # :next, :last, :first, :prev, :self
      scope = scope.to_s.to_sym
      if @hyperlinks[scope]
        load_from @hyperlinks[scope]
        return self.items
      end

      raise StopIteration
    end

    def refresh
      fetch :self
    end

    def create(attrs={})
      attrs = attrs.attributes if attrs.is_a?(Finix::Resource)
      attrs = Finix::Utils.indifferent_read_access attrs
      href = @hyperlinks[:self]
      if @resource_class.nil?
        @resource_class = Finix.from_href(href)
      end
      @resource_class.new(attrs, href).save
    end

    private

    def load_from(url, params = {})
      params ||= {}

      response = Finix.get url, params
      body = Finix::Utils.indifferent_read_access response.body

      links = body.delete('_links')
      links.each { |key, link| @hyperlinks[key.to_sym] = link[:href] }

      @attributes = {} # clear attributes
      if body.has_key? '_embedded'
        resource_name, resources = body.delete('_embedded').first
        @resource_class = Finix.from_hypermedia_registry resource_name
        @attributes['items'] = resources.map { |item| @resource_class.construct_from_response item }
        @attributes['page'] = body.delete('page')
      end
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
finix-0.7 lib/finix/pagination.rb