Module: Universa::Lazy

Defined in:
lib/universa/lazy.rb

Overview

Add class-level lazy declaration like:

class Test
    lazy(:foo) {
      puts "foo calculated"
      "bar"
    }

t = Test.new
t.foo # "foo calculated" -> "bar"
t.foo #=> "bar"

Constant Summary collapse

@@lazy_creation_mutex =

prevent from creation multiple instances of LazyValue’s

Mutex.new

Class Method Summary collapse

Class Method Details

.included(other) ⇒ Object



56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/universa/lazy.rb', line 56

def Lazy.included(other)


  # @!method lazy(name, &block)
  # Provides create lazy instance variable calculated by a provided block
  # @param [String] name of the created field
  # @return [string] Returns the greeting.
  # @yield calculates the value for the variable

  def other.lazy(name, &block)
    define_method(name.to_sym) {
      x = @@lazy_creation_mutex.synchronize {
        cache_name = :"@__#{name}__cache"
        if !(x = instance_variable_get(cache_name))
          x = LazyValue.new { instance_exec &block }
          instance_variable_set(cache_name, x)
        end
        x
      }
      x.get
    }
  end
end