Class: ThinModels::LazyArray::Memoized

Inherits:
MemoizedLength show all
Defined in:
lib/thin_models/lazy_array.rb

Overview

This additionally memoizes the full contents of the array once it’s been fully each’d one time. The memoized full contents will then be used for future calls to #each (and hence all the other enumerable methods) and #[]. #to_a directly returns the memoized array once available.

As with MemoizedLength, your extension points are now #_each, #_length and #slice_from_start_and_length

Direct Known Subclasses

Mapped

Defined Under Namespace

Classes: Mapped

Instance Method Summary collapse

Methods inherited from MemoizedLength

#_length, #length

Methods inherited from ThinModels::LazyArray

#empty?, #first, #initialize, #join, #last, #length, #map, #size, #slice_from_start_and_length, #to_json

Constructor Details

This class inherits a constructor from ThinModels::LazyArray

Instance Method Details

#[](*p) ⇒ Object Also known as: slice



191
192
193
# File 'lib/thin_models/lazy_array.rb', line 191

def [](*p)
  @to_a ? @to_a[*p] : super
end

#each(&b) ⇒ Object



173
174
175
176
177
178
179
180
181
182
183
# File 'lib/thin_models/lazy_array.rb', line 173

def each(&b)
  if @to_a
    @to_a.each(&b)
  else
    result = []
    _each {|item| yield item; result << item}
    @length = result.length
    @to_a = result
  end
  self
end

#inspectObject



196
197
198
199
200
201
202
203
204
# File 'lib/thin_models/lazy_array.rb', line 196

def inspect
  if @to_ary
    "[ThinModels::LazyArray: #{@to_ary.inspect[1..-1]}]"
  elsif @length
    "[ThinModels::LazyArray(length=#{@length}):...]"
  else
    "[ThinModels::LazyArray:...]"
  end
end

#to_aObject Also known as: entries, to_ary



185
186
187
# File 'lib/thin_models/lazy_array.rb', line 185

def to_a
  @to_a || super
end