Module: CoreEx::Module::AttrOnce

Included in:
Module
Defined in:
lib/core_ex/module/attr_once.rb

Instance Method Summary collapse

Instance Method Details

#attr_once(*ids) ⇒ Object

You can use this method as you use attr_reader. Must be used only with immutable object.

This method is imported from the Date implementation. It provides a way to compute only once the value of getter. Basically, the first time, the getter is used, its result is computed and stored in an attribute with the same name. The second times only the attribute is returned.



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/core_ex/module/attr_once.rb', line 19

def attr_once(*ids)
  for id in ids
    module_eval <<-"end;", __FILE__, __LINE__
      alias_method :__#{id.to_i}__, :#{id.to_s}
      private :__#{id.to_i}__
      def #{id.to_s}(*args, &block)
      if defined? @__#{id.to_i}__
          @__#{id.to_i}__
        elsif ! self.frozen?
          @__#{id.to_i}__ ||= __#{id.to_i}__(*args, &block)
        else
          __#{id.to_i}__(*args, &block)
        end
      end
    end;
  end
end