Sha256: d1fb457046b76ab35b0e2c25dd6f7f35a060f34aef45546ec695e1ccae746fbd

Contents?: true

Size: 1.12 KB

Versions: 3

Compression:

Stored size: 1.12 KB

Contents

module Emites
  module Entities

    class 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)
        parsed_body[page_rel].match(PAGE_REGEX)[1].to_i rescue nil
      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_body
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
emites-client-0.1.4 lib/emites/entities/collection.rb
emites-client-0.1.3 lib/emites/entities/collection.rb
emites-client-0.1.2 lib/emites/entities/collection.rb