class Everypolitician::Popolo::Collection

Attributes

documents[R]
popolo[R]

Public Class Methods

entity_class(entity = nil) click to toggle source

set the class that represents individual items in the collection

# File lib/everypolitician/popolo/collection.rb, line 13
def self.entity_class(entity = nil)
  @entity_class ||= entity
end
new(documents, popolo = nil) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 17
def initialize(documents, popolo = nil)
  @entity_class = {}
  @documents = documents ? documents.map { |p| class_for_entity(p).new(p, popolo) } : []
  @popolo = popolo
  @indexes = {}
  @of_collection = {}
end

Public Instance Methods

-(other) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 29
def -(other)
  other_ids = Set.new(other.documents.map(&:id))
  documents.reject { |d| other_ids.include?(d.id) }
end
each(&block) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 25
def each(&block)
  documents.each(&block)
end
empty?() click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 42
def empty?
  count.zero?
end
find_by(attributes = {}) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 34
def find_by(attributes = {})
  where(attributes).first
end
of_collection(collection) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 46
def of_collection(collection)
  @of_collection[collection] ||= new_collection(select { |e| e.class == collection.entity_class }, collection)
end
where(attributes = {}) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 38
def where(attributes = {})
  new_collection(attributes.map { |k, v| index_for(k.to_sym)[v].to_a }.reduce(:&))
end

Private Instance Methods

class_for_entity(_document) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 60
def class_for_entity(_document)
  self.class.entity_class
end
index_for(attr) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 52
def index_for(attr)
  @indexes[attr] ||= group_by(&attr)
end
new_collection(entities, klass = self.class) click to toggle source
# File lib/everypolitician/popolo/collection.rb, line 56
def new_collection(entities, klass = self.class)
  klass.new(entities.to_a.map(&:document), popolo)
end