File: lazy.rb

package info (click to toggle)
ruby-grit 2.8.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 336 kB
  • sloc: ruby: 3,643; makefile: 4
file content (35 lines) | stat: -rw-r--r-- 745 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
##
# 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