Sha256: 8f2bb524d1268edc88cbc1160437f92dd382edce90fff7c6c37de17fa42781b1

Contents?: true

Size: 1.18 KB

Versions: 6

Compression:

Stored size: 1.18 KB

Contents

# frozen_string_literal: true

module ROM
  # @api private
  module Memoizable
    MEMOIZED_HASH = {}

    module ClassInterface
      # @api private
      def memoize(*names)
        prepend(Memoizer.new(self, names))
      end

      def new(*)
        obj = super
        obj.instance_variable_set(:'@__memoized__', MEMOIZED_HASH.dup)
        obj
      end
    end

    def self.included(klass)
      super
      klass.extend(ClassInterface)
    end

    attr_reader :__memoized__

    # @api private
    class Memoizer < Module
      attr_reader :klass
      attr_reader :names

      # @api private
      def initialize(klass, names)
        @names = names
        @klass = klass
        define_memoizable_names!
      end

      private

      # @api private
      def define_memoizable_names!
        names.each do |name|
          meth = klass.instance_method(name)

          if meth.parameters.size > 0
            define_method(name) do |*args|
              __memoized__[:"#{name}_#{args.hash}"] ||= super(*args)
            end
          else
            define_method(name) do
              __memoized__[name] ||= super()
            end
          end
        end
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rom-core-5.1.2 lib/rom/support/memoizable.rb
rom-core-5.1.1 lib/rom/support/memoizable.rb
rom-core-5.1.0 lib/rom/support/memoizable.rb
rom-core-5.0.2 lib/rom/support/memoizable.rb
rom-core-5.0.1 lib/rom/support/memoizable.rb
rom-core-5.0.0 lib/rom/support/memoizable.rb