Class: Ampere::Collection

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

Overview

Collections are search results from queries. They can be used like arrays, but you cannot add anything to them.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model_class, array = []) ⇒ Collection

Instance methods ########################################################



14
15
16
17
# File 'lib/ampere/collection.rb', line 14

def initialize(model_class, array = [])
  @raw_array = array
  @model = model_class
end

Instance Attribute Details

#modelObject (readonly)

Returns the value of attribute model.



10
11
12
# File 'lib/ampere/collection.rb', line 10

def model
  @model
end

#raw_arrayObject (readonly)

Returns the value of attribute raw_array.



9
10
11
# File 'lib/ampere/collection.rb', line 9

def raw_array
  @raw_array
end

Instance Method Details

#==(other) ⇒ Object



50
51
52
53
54
# File 'lib/ampere/collection.rb', line 50

def ==(other)
  if other.is_a?(Array) then
    to_a == other
  end
end

#[](idx) ⇒ Object

Index into the search results. Lazily loads models when they’re accessed.



31
32
33
34
35
36
37
38
# File 'lib/ampere/collection.rb', line 31

def [](idx)
  if @raw_array[idx].is_a?(Ampere::Model) then
    @raw_array[idx]
  else
    # This is still an ID. Find it.
    @raw_array[idx] = @model.find(@raw_array[idx])
  end
end

#eachObject



19
20
21
22
23
24
25
26
27
28
# File 'lib/ampere/collection.rb', line 19

def each
  @raw_array.each_with_index do |x, i|
    if x.is_a?(Ampere::Model) then
      yield(x)
    else
      raw_array[i] = @model.find(x)
      yield(raw_array[i])
    end
  end
end

#empty?Boolean

Delegates to internal array.

Returns:

  • (Boolean)


41
42
43
# File 'lib/ampere/collection.rb', line 41

def empty?
  @raw_array.empty?
end

#lastObject

Returns the last item.



46
47
48
# File 'lib/ampere/collection.rb', line 46

def last
  self[-1]
end