Sha256: a57af009ef8f09567a161363309db52f595cd46ec33c27cdff5db260cec9db33

Contents?: true

Size: 1.47 KB

Versions: 12

Compression:

Stored size: 1.47 KB

Contents

module Kernel #:nodoc:

  # Directive for making your functions faster by trading
  # space for time. When you "memoize" a method/function
  # using #once its results are cached so that later calls
  # with the same arguments return results from the cache
  # instead of recalculating them.
  #
  #   class T
  #     def initialize(a)
  #       @a = a
  #     end
  #     def a
  #       "#{@a ^ 3 + 4}"
  #     end
  #     once :a
  #   end
  #
  #   t = T.new
  #   t.a.__id__ == t.a.__id__  #=> true
  #
  # This method can also be used at the instance level
  # to cache singleton/eigen methods.
  #
  # Note, this method used to be called +cache+ along with
  # it's other alias #memoize, but +once+ is the term used
  # in PickAxe so it has been adopted instead. The #memoize
  # alias has also been retained.
  #
  # CREDIT Robert Feldt
  #
  def once(*ids)
    if ids.empty?
      @_once ||= Hash::new{|h,k| h[k]={}}
    else
      base = (Module === self ? self : (class << self; self; end))
      ids.each do |m|
        base.module_eval <<-code
          alias_method '#{ m }:once', '#{ m }'
          private '#{ m }:once'
          def #{ m }(*__a__,&__b__)
            c = once['#{ m }']
            k = [__a__,__b__]
            if c.has_key? k
              c[k]
            else
              c[k] = __send__('#{ m }:once',*__a__,&__b__)
            end
          end
        code
      end
    end
  end

  # +once+ is also widely known as +memoize+.
  alias_method :memoize, :once

end

Version data entries

12 entries across 12 versions & 2 rubygems

Version Path
rbgccxml-1.1.0 lib/vendor/facets/once.rb
rbgccxml-1.0.4 lib/vendor/facets/once.rb
rbgccxml-1.0.3 lib/vendor/facets/once.rb
rbgccxml-1.0.2 lib/vendor/facets/once.rb
rbgccxml-1.0.1 lib/vendor/facets/once.rb
rbgccxml-1.0 lib/vendor/facets/once.rb
facets-2.8.4 lib/more/facets/once.rb
facets-2.8.3 lib/more/facets/once.rb
facets-2.8.2 lib/more/facets/once.rb
facets-2.8.1 lib/more/facets/once.rb
facets-2.8.0 lib/more/facets/once.rb
facets-2.7.0 lib/more/facets/once.rb