Sha256: 1f415f55b4e05843895414a28b7b468f41db7dc9018e8eca21c8c3845332dd5c

Contents?: true

Size: 1.32 KB

Versions: 16

Compression:

Stored size: 1.32 KB

Contents

module Reviewed
  class Collection
    include Enumerable

    extend Forwardable

    def_delegators :@items, :<<, :[], :[]=, :each, :first, :last, :length, :concat, :map, :collect, :empty?

    attr_accessor :raw_response, :page_attributes, :klass, :items, :params, :client

    def initialize(client, klass, response, params={})
      body = response.body
      data = body.data

      @client = client
      @klass = klass
      @params = params
      @items = []
      @page_attributes = body.pagination

      data.each do |obj|
        self.items << klass.new(obj)
      end
    end

    def limit_value
      per_page
    end

    def num_pages
      total_pages
    end

    def total_count
      total
    end

    def next_page
      return nil if @page_attributes[:last_page]
      fetch_page(@page_attributes[:next_page])
    end

    def previous_page
      return nil if @page_attributes[:first_page]
      fetch_page(@page_attributes[:previous_page])
    end

    def method_missing(sym, *args, &block)
      clean_sym = sym.to_s.gsub(/\?/, '').to_sym
      if @page_attributes.has_key?(clean_sym)
        @page_attributes[clean_sym]
      else
        super
      end
    end

    private

    def fetch_page(page=nil)
      self.params[:page] = page
      client.send(klass.association_name).where(self.params)
    end
  end
end

Version data entries

16 entries across 16 versions & 1 rubygems

Version Path
reviewed-0.2.2 lib/reviewed/collection.rb
reviewed-0.2.1 lib/reviewed/collection.rb
reviewed-0.2.0 lib/reviewed/collection.rb
reviewed-0.1.4 lib/reviewed/collection.rb
reviewed-0.1.32 lib/reviewed/collection.rb
reviewed-0.1.31 lib/reviewed/collection.rb
reviewed-0.1.30 lib/reviewed/collection.rb
reviewed-0.1.29 lib/reviewed/collection.rb
reviewed-0.1.28 lib/reviewed/collection.rb
reviewed-0.1.27 lib/reviewed/collection.rb
reviewed-0.1.26 lib/reviewed/collection.rb
reviewed-0.1.25 lib/reviewed/collection.rb
reviewed-0.1.24 lib/reviewed/collection.rb
reviewed-0.1.23 lib/reviewed/collection.rb
reviewed-0.1.22 lib/reviewed/collection.rb
reviewed-0.1.21 lib/reviewed/collection.rb