Sha256: b6f3efc7e5247b31d2cf72225b2f2eaf6c8d621c12d5b667030e6cd4acac3f13
Contents?: true
Size: 1.82 KB
Versions: 8
Compression:
Stored size: 1.82 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] @resource_class = Finix.from_hypermedia_registry href, attrs @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 do |attrs| cls = Finix.from_hypermedia_registry resource_name, attrs cls.construct_from_response attrs end @attributes['page'] = body.delete('page') end end end end
Version data entries
8 entries across 8 versions & 1 rubygems