Class: Abstractivator::Lazy

Inherits:
BasicObject
Defined in:
lib/abstractivator/lazy.rb

Overview

A transparent wrapper for delaying evaluation. Usage: v = lazy { 1 + 2 } This delays the addition until the value is actually needed, i.e., a method is called on it. The wrapper is “transparent” in that it acts as much as possible like the wrapped object itself. For example: lazy { 42 }.class ==> Fixnum Don’t use this for mission critical code. Don’t pass lazy objects across API boundaries.

Instance Method Summary collapse

Constructor Details

#initialize(&make) ⇒ Lazy

Returns a new instance of Lazy.



14
15
16
# File 'lib/abstractivator/lazy.rb', line 14

def initialize(&make)
  @make = make
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



27
28
29
# File 'lib/abstractivator/lazy.rb', line 27

def method_missing(method, *args, **kws, &block)
  __lazy_ensure_obj.proxy_send(method, *args, **kws, &block)
end

Instance Method Details

#!Object



39
40
41
# File 'lib/abstractivator/lazy.rb', line 39

def !
  !__lazy_ensure_obj
end

#!=(other) ⇒ Object



35
36
37
# File 'lib/abstractivator/lazy.rb', line 35

def !=(other)
  __lazy_ensure_obj != other
end

#==(other) ⇒ Object



31
32
33
# File 'lib/abstractivator/lazy.rb', line 31

def ==(other)
  __lazy_ensure_obj == other
end

#inspectObject



72
73
74
# File 'lib/abstractivator/lazy.rb', line 72

def inspect
  "#<Abstractivator::Lazy:#{@make ? '' : @obj.class.name + ':'}0x#{__id__.to_s(16).rjust(8, '0')}>"
end

#to_aObject

Force ruby to delegate to wrapped object. Ruby’s C implementation makes assumptions about object type. This is required for explicit array coercion:

x = 1
a = *x
(a == [1])


63
64
65
66
67
68
69
70
# File 'lib/abstractivator/lazy.rb', line 63

def to_a
  __lazy_ensure_obj
  if @obj.respond_to?(:to_a)
    @obj.to_a
  else
    nil
  end
end

#to_aryObject

Force ruby to delegate to wrapped object. Ruby’s C implementation makes assumptions about object type. This is required for implicit array coercion:

a = [1, 2]
x, y = a


48
49
50
51
52
53
54
55
# File 'lib/abstractivator/lazy.rb', line 48

def to_ary
  __lazy_ensure_obj
  if @obj.respond_to?(:to_ary)
    @obj.to_ary
  else
    nil
  end
end