Module: Lazy

Included in:
Grit::Commit, Grit::Tag, Grit::Tree
Defined in:
lib/grit/lazy.rb

Overview

Allows attributes to be declared as lazy, meaning that they won't be computed until they are asked for.

Works by delegating each lazy_reader to a cached lazy_source method.

class Person

lazy_reader :eyes

def lazy_source
  OpenStruct.new(:eyes => 2)
end

end

>> Person.new.eyes

> 2

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(klass) ⇒ Object


19
20
21
# File 'lib/grit/lazy.rb', line 19

def self.extended(klass)
  klass.send(:attr_writer, :lazy_source)
end

Instance Method Details

#lazy_reader(*args) ⇒ Object


23
24
25
26
27
28
29
30
31
32
33
34
# File 'lib/grit/lazy.rb', line 23

def lazy_reader(*args)
  args.each do |arg|
    ivar = "@#{arg}"
    define_method(arg) do
      if instance_variable_defined?(ivar)
        val = instance_variable_get(ivar)
        return val if val
      end
      instance_variable_set(ivar, (@lazy_source ||= lazy_source).send(arg))
    end
  end
end