Sha256: bf2743a329919da1aeb186b80031b109df8258beb3c9722ba039dd6c81873872

Contents?: true

Size: 1.15 KB

Versions: 13

Compression:

Stored size: 1.15 KB

Contents

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

13 entries across 13 versions & 1 rubygems

Version Path
rom-core-4.2.1 lib/rom/support/memoizable.rb
rom-core-4.2.0 lib/rom/support/memoizable.rb
rom-core-4.1.2 lib/rom/support/memoizable.rb
rom-core-4.1.1 lib/rom/support/memoizable.rb
rom-core-4.1.0 lib/rom/support/memoizable.rb
rom-core-4.0.2 lib/rom/support/memoizable.rb
rom-core-4.0.1 lib/rom/support/memoizable.rb
rom-core-4.0.0 lib/rom/support/memoizable.rb
rom-core-4.0.0.rc2 lib/rom/support/memoizable.rb
rom-core-4.0.0.rc1 lib/rom/support/memoizable.rb
rom-core-4.0.0.beta3 lib/rom/support/memoizable.rb
rom-core-4.0.0.beta2 lib/rom/support/memoizable.rb
rom-core-4.0.0.beta1 lib/rom/support/memoizable.rb