Sha256: da81939ebe04da94194d8cf67cd6b0fd817d472eac70ad05b483cb6da6f3291e

Contents?: true

Size: 1.44 KB

Versions: 8

Compression:

Stored size: 1.44 KB

Contents

require File.join(__dir__, 'proxy.rb')

# A collection is a special type of data
# that contains multiple items
class LHS::Collection < LHS::Proxy

  def total
    _data._raw['total']
  end

  def limit
    _data._raw['limit']
  end

  def offset
    _data._raw['offset']
  end

  def href
    _data._raw['href']
  end

  def _collection
    raw = _data._raw if _data._raw.is_a?(Array)
    raw ||= _data._raw['items']
    Collection.new(raw, _data, _data._service)
  end

  def _raw
    _data._raw
  end

  protected

  def method_missing(name, *args, &block)
    value = _collection.send(name, *args, &block)
    if value.is_a? Hash
      data = LHS::Data.new(value, _data)
      item = LHS::Item.new(data)
      LHS::Data.new(item, _data)
    else
      value
    end
  end

  def respond_to_missing?(name, include_all = false)
    _collection.respond_to?(name, include_all)
  end

  private

  # The internal collection class that includes enumerable
  # and insures to return LHS::Items in case of iterating items
  class Collection
    include Enumerable

    attr_accessor :raw
    delegate :last, :sample, :[], :present?, :blank?, :empty?, to: :raw

    def initialize(raw, parent, service)
      self.raw = raw
      @parent = parent
      @service = service
    end

    def each(&block)
      raw.each do |item|
        if item.is_a? Hash
          yield LHS::Data.new(item, @parent, @service)
        else
          yield item
        end
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
lhs-1.6.1 lib/lhs/collection.rb
lhs-1.6.0 lib/lhs/collection.rb
lhs-2.0.0 lib/lhs/collection.rb
lhs-1.5.0 lib/lhs/collection.rb
lhs-1.4.0 lib/lhs/collection.rb
lhs-1.3.1 lib/lhs/collection.rb
lhs-1.3.0 lib/lhs/collection.rb
lhs-1.2.3 lib/lhs/collection.rb