Sha256: 5fe51e9a893c0ece0424052f00293296b0caef39e2235c92bbe4565b03f9f82a

Contents?: true

Size: 745 Bytes

Versions: 40

Compression:

Stored size: 745 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 self.extended(klass)
    klass.send(:attr_writer, :lazy_source)
  end

  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

Version data entries

40 entries across 40 versions & 9 rubygems

Version Path
gitlab-grit-2.8.3 lib/grit/lazy.rb
gitlab-grit-2.8.2 lib/grit/lazy.rb
gitlab-grit-2.8.1 lib/grit/lazy.rb
gitlab-grit-2.8.0 lib/grit/lazy.rb
gitlab-grit-2.7.3 lib/grit/lazy.rb
gitlab-grit-2.6.12 lib/grit/lazy.rb
gitlab-grit-2.7.2 lib/grit/lazy.rb
gitlab-grit-2.6.11 lib/grit/lazy.rb
gitlab-grit-2.7.1 lib/grit/lazy.rb
gitlab-grit-2.6.10 lib/grit/lazy.rb
gitlab-grit-2.7.0 lib/grit/lazy.rb
gitlab-grit-2.6.9 lib/grit/lazy.rb
gitlab-grit-2.6.8 lib/grit/lazy.rb
gitlab-grit-2.6.7 lib/grit/lazy.rb
gitlab-grit-2.6.6 lib/grit/lazy.rb
gitlab-grit-2.6.5 lib/grit/lazy.rb
gitlab-grit-2.6.4 lib/grit/lazy.rb
gitlab-grit-2.6.3 lib/grit/lazy.rb
gitlab-grit-2.6.2 lib/grit/lazy.rb
gitlab-grit-2.5.2 lib/grit/lazy.rb