Class: StrokeDB::LazyArray

Inherits:
BlankSlate show all
Defined in:
lib/strokedb/util/lazy_array.rb

Overview

Lazy loads items from array.

Lazy arrays are backed by Proc returning regular array on first call retrieving it from @load_with_proc.

Example:

ary = LazyArray.new.load_with { Time.now.to_s.split(/\s/) }

On first attempt to access ary (including inspect) it will evaluate load_with’s Proc and update own content with its result:

ary
  # ==> ["Mon", "Mar", "17", "10:35:52", "+0200", "2008"]

Constant Summary

Constants inherited from BlankSlate

BlankSlate::MethodMapping

Instance Method Summary collapse

Constructor Details

#initialize(*args) ⇒ LazyArray

Returns a new instance of LazyArray.



18
19
20
21
# File 'lib/strokedb/util/lazy_array.rb', line 18

def initialize(*args)
  @load_with_proc = proc {|v| v}
  @array = Array.new(*args)
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(sym, *args, &blk) ⇒ Object



34
35
36
37
38
39
40
41
# File 'lib/strokedb/util/lazy_array.rb', line 34

def method_missing sym, *args, &blk
  if @array.respond_to? sym
    load!
    @array.__send__ sym, *args, &blk
  else
    super
  end
end

Instance Method Details

#classObject

Make it look like array for outer world



30
31
32
# File 'lib/strokedb/util/lazy_array.rb', line 30

def class
  Array
end

#load_with(&block) ⇒ Object

Proc to execute lazy loading



24
25
26
27
# File 'lib/strokedb/util/lazy_array.rb', line 24

def load_with(&block)
  @load_with_proc = block
  self
end