Sha256: 9956fb203f726c1b5b3e2c7e35268d1c6fb3e0fc1afaa25a37fe80376fe77e06

Contents?: true

Size: 980 Bytes

Versions: 7

Compression:

Stored size: 980 Bytes

Contents

class NexaasID::Entities::Collection < Base
  extend Forwardable

  PAGE_REGEX = /page=(\d+)/

  attr_reader :total
  def_delegators :@collection, :first, :last, :each, :map, :count, :empty?, :any?

  def initialize(response, entity_class)
    @response = response
    @entity_class = entity_class
    @total = parsed_body['count'].to_i
    @collection = []
   end

  def self.build(response, entity_class)
    self.new(response, entity_class).build
  end

  def build
    build_collection
    self
  end

  def next_page
    page_for('next')
  end

  def previous_page
    page_for('previous')
  end

  def to_a
    @collection.clone
  end

  private

  def page_for(page_rel)
    match = parsed_body[page_rel].match(PAGE_REGEX)
    return match[1].to_i if match
  end

  def build_collection
    parsed_body['collection'].each do |attributes|
      @collection.push(@entity_class.new(attributes))
    end
  end

  def parsed_body
    @parsed_body ||= @response.parsed
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
nexaas_id-client-0.7.4 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.7.3 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.7.2 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.7.1 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.7.0 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.6.0 lib/nexaas_id/entities/collection.rb
nexaas_id-client-0.5.0 lib/nexaas_id/entities/collection.rb