Sha256: dff17ed18502e9d3160bf6d00df31e2e92f0ca40e9f2e327db93b4aab3ecec1f

Contents?: true

Size: 1.07 KB

Versions: 26

Compression:

Stored size: 1.07 KB

Contents

# frozen_string_literal: true

module DeepCover
  bootstrap

  # Memoize is a quick way to prepend a module that defines
  # the memoized methods as `@_cache ||= super.freeze`
  # It also refines `freeze` to precache memoized methods
  #
  module Memoize
    def self.included(base)
      base.extend ClassMethods
    end

    def freeze
      self.class.memoized.each do |method|
        send method
      end
      super
    end

    module ClassMethods
      def memoized
        @memoized ||= [].freeze
      end

      def memoizer_module
        @memoizer_module ||= begin
          mod = const_set(:Memoizer, Module.new)
          prepend mod
          mod
        end
      end

      def memoize(*methods)
        @memoized = (memoized | methods).freeze

        methods.each do |method|
          memoizer_module.module_eval <<-RUBY, __FILE__, __LINE__ + 1
            def #{method}                    # def foo
              @_#{method} ||= super.freeze   #   @_foo ||= super.freeze
            end                              # end
          RUBY
        end
      end
    end
  end
end

Version data entries

26 entries across 26 versions & 2 rubygems

Version Path
deep-cover-core-1.1.0 lib/deep_cover/memoize.rb
deep-cover-core-1.0.0 lib/deep_cover/memoize.rb
deep-cover-core-0.8.1 lib/deep_cover/memoize.rb
deep-cover-core-0.8.0 lib/deep_cover/memoize.rb
deep-cover-core-0.7.10 lib/deep_cover/memoize.rb
deep-cover-core-0.7.9 lib/deep_cover/memoize.rb
deep-cover-core-0.7.8 lib/deep_cover/memoize.rb
deep-cover-core-0.7.7 lib/deep_cover/memoize.rb
deep-cover-core-0.7.6 lib/deep_cover/memoize.rb
deep-cover-core-0.7.5 lib/deep_cover/memoize.rb
deep-cover-core-0.7.4 lib/deep_cover/memoize.rb
deep-cover-core-0.7.3 lib/deep_cover/memoize.rb
deep-cover-core-0.7.2 lib/deep_cover/memoize.rb
deep-cover-core-0.7.1 lib/deep_cover/memoize.rb
deep-cover-core-0.7.0 lib/deep_cover/memoize.rb
deep-cover-core-0.6.4 lib/deep_cover/memoize.rb
deep-cover-core-0.6.3 lib/deep_cover/memoize.rb
deep-cover-core-0.6.3.pre lib/deep_cover/memoize.rb
deep-cover-0.6.2 lib/deep_cover/memoize.rb
deep-cover-0.6.1 lib/deep_cover/memoize.rb