Class: Everypolitician::Popolo::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/everypolitician/popolo/collection.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(documents, popolo = nil) ⇒ Collection

Returns a new instance of Collection.



15
16
17
18
19
20
21
# File 'lib/everypolitician/popolo/collection.rb', line 15

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

Instance Attribute Details

#documentsObject (readonly)

Returns the value of attribute documents.



6
7
8
# File 'lib/everypolitician/popolo/collection.rb', line 6

def documents
  @documents
end

#popoloObject (readonly)

Returns the value of attribute popolo.



7
8
9
# File 'lib/everypolitician/popolo/collection.rb', line 7

def popolo
  @popolo
end

Class Method Details

.entity_class(entity = nil) ⇒ Object

set the class that represents individual items in the collection



11
12
13
# File 'lib/everypolitician/popolo/collection.rb', line 11

def self.entity_class(entity = nil)
  @entity_class ||= entity
end

Instance Method Details

#-(other) ⇒ Object



27
28
29
30
# File 'lib/everypolitician/popolo/collection.rb', line 27

def -(other)
  other_ids = Set.new(other.documents.map(&:id))
  documents.reject { |d| other_ids.include?(d.id) }
end

#each(&block) ⇒ Object



23
24
25
# File 'lib/everypolitician/popolo/collection.rb', line 23

def each(&block)
  documents.each(&block)
end

#empty?Boolean

Returns:

  • (Boolean)


40
41
42
# File 'lib/everypolitician/popolo/collection.rb', line 40

def empty?
  count.zero?
end

#find_by(attributes = {}) ⇒ Object



32
33
34
# File 'lib/everypolitician/popolo/collection.rb', line 32

def find_by(attributes = {})
  where(attributes).first
end

#of_collection(collection) ⇒ Object



44
45
46
# File 'lib/everypolitician/popolo/collection.rb', line 44

def of_collection(collection)
  @of_collection[collection] ||= new_collection(select { |e| e.class == collection.entity_class }, collection)
end

#where(attributes = {}) ⇒ Object



36
37
38
# File 'lib/everypolitician/popolo/collection.rb', line 36

def where(attributes = {})
  new_collection(attributes.map { |k, v| index_for(k.to_sym)[v].to_a }.reduce(:&))
end