Sha256: d79087dd6d68f2c64c173199fd5ad12824361f723c95838ff33cb128c16b7a7a

Contents?: true

Size: 728 Bytes

Versions: 31

Compression:

Stored size: 728 Bytes

Contents

##
# 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
#
module Lazy
  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
end

Object.extend Lazy unless Object.ancestors.include? Lazy

Version data entries

31 entries across 31 versions & 13 rubygems

Version Path
boof-grit-1.1.2 lib/grit/lazy.rb
davetron5000-grit-1.1.2 lib/grit/lazy.rb
davetron5000-grit-1.1.3 lib/grit/lazy.rb
joelmoss-grit-1.1.4 lib/grit/lazy.rb
joelmoss-grit-1.1.5 lib/grit/lazy.rb
joelmoss-grit-1.1.6 lib/grit/lazy.rb
kubicek-grit-1.0.3 lib/grit/lazy.rb
kubicek-grit-1.1.1.1 lib/grit/lazy.rb
kubicek-grit-1.1.1 lib/grit/lazy.rb
mojombo-grit-0.9.4 lib/grit/lazy.rb
mojombo-grit-1.1.1 lib/grit/lazy.rb
pjhyett-grit-0.9.11 lib/grit/lazy.rb
pjhyett-grit-0.9.12 lib/grit/lazy.rb
robinluckey-grit-1.1.1 lib/grit/lazy.rb
schacon-grit-0.9.4 lib/grit/lazy.rb
schacon-grit-1.1.1 lib/grit/lazy.rb
square-circle-triangle-grit-1.1.2 lib/grit/lazy.rb
square-circle-triangle-grit-1.1.3 lib/grit/lazy.rb
square-circle-triangle-grit-1.1.4 lib/grit/lazy.rb
steveh-grit-1.1.1 lib/grit/lazy.rb