Sha256: c090786e07cf9b8a4989ba0e27afaa759a4d7db4819061158e33e4907f1bcd49

Contents?: true

Size: 1.17 KB

Versions: 11

Compression:

Stored size: 1.17 KB

Contents

module Lookbook
  class EntityCollection
    include Enumerable

    delegate_missing_to :entities

    attr_reader :entities

    def initialize(entities = nil)
      @_cache = {}
      @entities = []
      add(entities)
    end

    def add(to_add = nil)
      Array(to_add).each do |entity|
        unless find_by_path(entity.path)
          @entities.push(entity)
        end
      end
      clear_cache
    end

    def find_by_id(id)
      id = Utils.id(id)
      entities.find { |entity| entity.id == id }
    end

    def find_by_path(path)
      entities.find { |entity| entity.path.to_s == path.to_s }
    end

    def next(entity)
      index = entities.find_index { |i| i.path == entity.path }
      entities[index + 1] unless index.nil?
    end

    def previous(entity)
      index = entities.find_index { |i| i.path == entity.path }
      entities[index - 1] if !index.nil? && index > 0
    end

    def each(&block)
      if block
        entities.sort.each { |entity| yield entity }
      else
        to_enum(:each)
      end
    end

    def flat_map(...)
      entities.map(...).map(&:to_a).flatten
    end

    protected

    def clear_cache
      @_cache = {}
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
lookbook-1.5.5 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.5.4 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.5.3 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.5.2 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.5.1 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.5.0 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.4.5 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.4.4 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.4.3 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.4.2 lib/lookbook/entities/collections/entity_collection.rb
lookbook-1.4.1 lib/lookbook/entities/collections/entity_collection.rb