Class: MagicArray

Inherits:
Object
  • Object
show all
Defined in:
lib/magic_array.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*attrs) ⇒ MagicArray

Returns a new instance of MagicArray.



7
8
9
10
11
# File 'lib/magic_array.rb', line 7

def initialize *attrs
  @elements = []
  @count = 0 unless @count
  self
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



13
14
15
# File 'lib/magic_array.rb', line 13

def method_missing m, *args, &block
  @elements.public_send m, args
end

Instance Attribute Details

#countObject

Returns the value of attribute count.



5
6
7
# File 'lib/magic_array.rb', line 5

def count
  @count
end

#elementsObject

Returns the value of attribute elements.



5
6
7
# File 'lib/magic_array.rb', line 5

def elements
  @elements
end

Class Method Details

.load_limit(attr = nil) ⇒ Object



65
66
67
# File 'lib/magic_array.rb', line 65

def load_limit attr=nil
  @@load_limit = attr || 100
end

Instance Method Details

#[](index) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/magic_array.rb', line 17

def [] index
  case index
    when Range then
      if elements[index].empty? || elements[index].include?(nil)
        load_elements(index)
      else
        elements[index]
      end
    else
      elements[index] || load_element(index)
  end
end

#allObject



30
31
32
# File 'lib/magic_array.rb', line 30

def all
  self[0..(count-1)]
end

#load_element(index) ⇒ Object



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

def load_element index
  elements[index] = element_source index
end

#load_elements(range) ⇒ Object



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/magic_array.rb', line 38

def load_elements range
  iterative_range = if range.end < count || count == 0
                      range.dup
                    else
                      Range.new range.begin, count-1
                    end

  while iterative_range.count > 0
    limited_range = iterative_range.first(@@load_limit)
    iterative_range = Range.new(
        (
        limited_range.count < @@load_limit ?
            iterative_range.end+1 :
            iterative_range.begin+@@load_limit
        ),
        iterative_range.end
    )
    array = elements_source limited_range.first, limited_range.count
    limited_range.each_with_index do |element, index|
      elements[element] = array[index]
    end
  end
  elements[range]
end