public
Fork of Caged/gitnub
Description: A Gitk-like application written in RubyCocoa that looks like it belongs on a Mac. See the wiki for downloads and screenshots.
Homepage: http://alternateidea.com
Clone URL: git://github.com/drodriguez/gitnub.git
gitnub / grit / lib / grit / lazy.rb
100644 53 lines (50 sloc) 1.059 kb
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# Allows attributes to be declared as lazy, meaning that they won't be
# computed until they are asked for. Just mix this module in:
#
# class Foo
# include Lazy
# ...
# end
#
# To specify a lazy reader:
#
# lazy_reader :att
#
# Then, define a method called __bake__ that computes all your lazy
# attributes:
#
# def __bake__
# @att = ...
# end
#
# If you happen to have already done all the hard work, you can mark an instance
# as already baked by calling:
#
# __baked__
#
# That's it! (Tom Preston-Werner: rubyisawesome.com)
module Lazy
  module ClassMethods
    def lazy_reader(*args)
      args.each do |arg|
        define_method(arg) do
          val = instance_variable_get("@#{arg}")
          return val if val
          self.__prebake__
          instance_variable_get("@#{arg}")
        end
      end
    end
  end
  
  def __prebake__
    return if @__baked__
    self.__bake__
    @__baked__ = true
  end
  
  def __baked__
    @__baked__ = true
  end
  
  def self.included(base)
    base.extend(ClassMethods)
  end
end