Sha256: 2d61e2eba2d5e8269ff9566b28e92820b1f0e0e3761eb06b1b88e2ba83937b22

Contents?: true

Size: 1.48 KB

Versions: 8

Compression:

Stored size: 1.48 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

  delegate :select, to: :_collection

  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-2.2.2 lib/lhs/collection.rb
lhs-2.2.1 lib/lhs/collection.rb
lhs-2.2.0 lib/lhs/collection.rb
lhs-2.1.1 lib/lhs/collection.rb
lhs-2.1.0 lib/lhs/collection.rb
lhs-2.0.5 lib/lhs/collection.rb
lhs-2.0.4 lib/lhs/collection.rb
lhs-2.0.3 lib/lhs/collection.rb