Module: MaimaiNet::ModuleExt::MethodCache

Extended by:
HaveClassMethods
Included in:
MaimaiNet::Model::Either, MaimaiNet::Model::Generic, Page::Base
Defined in:
lib/maimai_net/module_ext.rb

Overview

allows registering methods into cacheable results.

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HaveClassMethods

class_method, included

Class Method Details

.included(cls) ⇒ void

This method returns an undefined value.

initializes internal data for method caching



384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
# File 'lib/maimai_net/module_ext.rb', line 384

def self.included(cls)
  cls.class_exec do
    include AddInternalMutex
  end

  super

  cls.class_exec do
    if singleton_class? then
      # define_method :singleton_method_added, method(:method_added).unbind
      singleton_class.undef_method :method_added
    else
      undef_method :singleton_method_added
    end
  end

  cls.instance_exec do
    proc_key_to_id = ->(h, k){
      case k
      when Integer
        h[k]
      when Float, NilClass, TrueClass, FalseClass
        fail KeyError, "invalid key"
      else
        h[k.object_id]
      end
    }

    @_cache_methods ||= []
    @_cache_results ||= Hash.new do |h, k|
      next h[k.to_sym] if h.key?(k.to_sym)
      h[k.to_sym] = Hash.new &proc_key_to_id
    end
  end
end

Instance Method Details

#singleton_method_added(meth) ⇒ Object

Hooks method that specified through cache_method with internal cache wrapper.

See Also:

  • #cache_method


221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'lib/maimai_net/module_ext.rb', line 221

def singleton_method_added(meth)
  singleton_class.class_exec do
    is_locked = false
    mutex = @_method_mutex.to_h.dig(:cache_method, meth)
    is_locked = mutex.locked? if mutex && mutex.locked?

    if @_cache_methods&.include?(meth) && !is_locked then
      alias_method :"raw_#{meth}", meth
      _cache_method(meth)
    end
  end

  super
end