Class: Mordor::Collection

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

Instance Method Summary collapse

Constructor Details

#initialize(klass, cursor) ⇒ Collection

Returns a new instance of Collection.



5
6
7
8
# File 'lib/mordor/collection.rb', line 5

def initialize(klass, cursor)
  @klass = klass
  @cursor = cursor
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method, *args, &block) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/mordor/collection.rb', line 26

def method_missing(method, *args, &block)
  if @cursor.respond_to?(method)
    self.class.new(@klass, @cursor.__send__(method, *args, &block))
  else
    super
  end
end

Instance Method Details

#eachObject



10
11
12
13
14
15
16
17
18
19
# File 'lib/mordor/collection.rb', line 10

def each
  @cursor.each do |element|
    if element.is_a? @klass
      yield element
    else
      yield @klass.new(element)
    end
  end
  @cursor.rewind! unless @cursor.is_a? Array
end

#merge(other_collection) ⇒ Object Also known as: +



38
39
40
# File 'lib/mordor/collection.rb', line 38

def merge(other_collection)
  Collection.new(@klass, (self.to_a + other_collection.to_a))
end

#merge!(other_collection) ⇒ Object



43
44
45
46
47
48
# File 'lib/mordor/collection.rb', line 43

def merge!(other_collection)
  unless @cursor.is_a? Array
    @cursor = @cursor.to_a
  end
  @cursor += other_collection.to_a
end

#size(regard_limits_and_offsets = true) ⇒ Object Also known as: count



21
22
23
# File 'lib/mordor/collection.rb', line 21

def size(regard_limits_and_offsets = true)
  @cursor.is_a?(Array) ? @cursor.count : @cursor.count(regard_limits_and_offsets)
end

#to_json(*args) ⇒ Object



34
35
36
# File 'lib/mordor/collection.rb', line 34

def to_json(*args)
  to_a.to_json(*args)
end