Module: Memery::ClassMethods

Defined in:
lib/memery.rb

Overview

Module for class methods

Instance Method Summary collapse

Instance Method Details

#memoize(method_name, condition: nil, ttl: nil) ⇒ Object

TODO: Resolve this rubocop:disable Metrics/MethodLength rubocop:disable Metrics/AbcSize rubocop:disable Metrics/CyclomaticComplexity rubocop:disable Metrics/PerceivedComplexity



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/memery.rb', line 41

def memoize(method_name, condition: nil, ttl: nil)
  original_visibility = Memery.method_visibility(self, method_name)

  original_method = memoized_methods[method_name] = instance_method(method_name)

  undef_method method_name

  define_method method_name do |*args, &block|
    if block || (condition && !instance_exec(&condition))
      return original_method.bind(self).call(*args, &block)
    end

    method_object_id = original_method.object_id

    store =
      ((@_memery_memoized_values ||= {})[method_name] ||= {})[method_object_id] ||= {}

    if store.key?(args) && (ttl.nil? || Memery.monotonic_clock <= store[args][:time] + ttl)
      return store[args][:result]
    end

    result = original_method.bind(self).call(*args)
    @_memery_memoized_values[method_name][method_object_id][args] =
      { result: result, time: Memery.monotonic_clock }
    result
  end

  ruby2_keywords method_name

  send original_visibility, method_name

  method_name
end

#memoized?(method_name) ⇒ Boolean

rubocop:enable Metrics/MethodLength rubocop:enable Metrics/AbcSize rubocop:enable Metrics/CyclomaticComplexity rubocop:enable Metrics/PerceivedComplexity

Returns:

  • (Boolean)


79
80
81
# File 'lib/memery.rb', line 79

def memoized?(method_name)
  memoized_methods.key?(method_name)
end

#memoized_methodsObject



32
33
34
# File 'lib/memery.rb', line 32

def memoized_methods
  @memoized_methods ||= {}
end