Sha256: cb54b1dfcb8edd2563019317ff9df4fb0f78cdf324bc87a0dfa0fe6cedf47a02

Contents?: true

Size: 1.12 KB

Versions: 4

Compression:

Stored size: 1.12 KB

Contents

# Copyright: Copyright (c) 2004  Nicolas Despres. All rights reserved.
# Author: Nicolas Despres  <polrop@lrde.epita.fr>.
# License: Gnu General Public License.

# $LastChangedBy: polrop $
# $Id: attr_once.rb 135 2005-01-28 12:43:31Z polrop $


class Module

  # 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.
  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

end # class Module

Version data entries

4 entries across 4 versions & 2 rubygems

Version Path
ttk-0.1.576 ruby_ex/module/attr_once.rb
ttk-0.1.580 ruby_ex/module/attr_once.rb
ttk-0.1.579 ruby_ex/module/attr_once.rb
vcs-0.2.148 ruby_ex/module/attr_once.rb