Sha256: 1b309fa6a2c18b6f72df671e4aaf080cc28bcb434a2ea29e7b77f802a4d8aa14

Contents?: true

Size: 1.98 KB

Versions: 17

Compression:

Stored size: 1.98 KB

Contents

# A collection is a special type of data
# that contains multiple items
class LHS::Collection < LHS::Proxy
  autoload :HandleNested,
    'lhs/concerns/collection/handle_nested'
  autoload :InternalCollection,
    'lhs/concerns/collection/internal_collection'

  include HandleNested
  include InternalCollection
  include Create

  METHOD_NAMES_EXLCUDED_FROM_WRAPPING = %w(to_a to_ary map).freeze

  delegate :select, :length, :size, to: :_collection
  delegate :_record, :_raw, to: :_data
  delegate :limit, :count, :total, :offset, :current_page, :start,
           :next?, :previous?, to: :_pagination

  def _pagination
    _record.pagination(_data)
  end

  def href
    return _data._raw[:href] if _data._raw.is_a? Hash
    nil
  end

  def _collection
    raw = _data._raw if _data._raw.is_a?(Array)
    raw ||= _data.access(input: _data._raw, record: _record)
    Collection.new(raw, _data, _record)
  end

  def collection?
    true
  end

  def item?
    false
  end

  def raw_items
    if _raw.is_a?(Array)
      _raw
    else
      access(input: _raw, record: _record)
    end
  end

  protected

  def method_missing(name, *args, &block)
    if _collection.respond_to?(name)
      value = _collection.send(name, *args, &block)
      record = LHS::Record.for_url(value[:href]) if value.is_a?(Hash) && value[:href]
      value = enclose_item_in_data(value) if value.is_a?(Hash)
      return value if METHOD_NAMES_EXLCUDED_FROM_WRAPPING.include?(name.to_s)
      wrap_return(value, record, name)
    elsif _data._raw.is_a?(Hash)
      get(name, *args)
    end
  end

  def respond_to_missing?(name, _include_all = false)
    # We accept every message that does not belong to set of keywords and is not a setter
    BLACKLISTED_KEYWORDS.exclude?(name.to_s) && !name.to_s[/=$/]
  end

  private

  # Encloses accessed collection item
  # by wrapping it in an LHS::Item
  def enclose_item_in_data(value)
    data = LHS::Data.new(value, _data)
    item = LHS::Item.new(data)
    LHS::Data.new(item, _data)
  end
end

Version data entries

17 entries across 17 versions & 1 rubygems

Version Path
lhs-14.1.1 lib/lhs/collection.rb
lhs-14.1.0 lib/lhs/collection.rb
lhs-14.0.3 lib/lhs/collection.rb
lhs-14.0.2 lib/lhs/collection.rb
lhs-14.0.1 lib/lhs/collection.rb
lhs-14.0.0 lib/lhs/collection.rb
lhs-13.2.3 lib/lhs/collection.rb
lhs-13.2.2 lib/lhs/collection.rb
lhs-13.2.1 lib/lhs/collection.rb
lhs-13.2.0 lib/lhs/collection.rb
lhs-13.1.0 lib/lhs/collection.rb
lhs-13.0.1 lib/lhs/collection.rb
lhs-13.0.0 lib/lhs/collection.rb
lhs-12.3.0 lib/lhs/collection.rb
lhs-12.2.1 lib/lhs/collection.rb
lhs-12.2.0 lib/lhs/collection.rb
lhs-12.1.0 lib/lhs/collection.rb