Module: ThreeScale::Backend::Memoizer::Decorator::ClassMethods
- Defined in:
- lib/3scale/backend/memoizer.rb
Defined Under Namespace
Modules: Helpers
Instance Method Summary collapse
-
#memoize(*methods) ⇒ Object
memoize :method, :other_method, …
-
#memoize_i(*methods) ⇒ Object
memoize_i :method, :other_method.
Instance Method Details
#memoize(*methods) ⇒ Object
memoize :method, :other_method, …
Decorate the methods passed in memoizing their results based on the parameters they receive using a key with the form: (ClassName|Instance).methodname[-param1[-param2]]
You can call this from a class on instance or class methods, and from a metaclass on instance methods, which actually are class methods.
CAVEAT: if you have an instance method named exactly as an existing class method you either memoize the instance method BEFORE defining the class method or use memoize_i on the instance method.
WARNING: do NOT use this memoize method on frequently called instance methods since you’ll have a noticeable overhead from the necessity to bind the method to the object.
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 |
# File 'lib/3scale/backend/memoizer.rb', line 230 def memoize(*methods) classkey = Memoizer.build_class_key self # get the base class of self so that we get rid of metaclasses klass = Helpers.get_instance_class self # make sure klass points to the klass that self is a metaclass of # in case we're being invoked from a metaclass methods.each do |m| # For each method, first search for a class method, which is the # common case. If not found, then look for an instance method. # begin key = Memoizer.build_method_key(classkey, m.to_s) original_method = klass.method m raise NameError unless original_method.owner == klass.singleton_class Helpers.memoize_class_method original_method, key, klass rescue NameError # If we cannot find a class method, try an instance method # before bailing out. memoize_i m end end end |
#memoize_i(*methods) ⇒ Object
memoize_i :method, :other_method
Forces memoization of methods which are instance methods in the current context level. This can be used to, for example, override the default look up when we have two methods, class and instance, which are named the same and we want to memoize both or only the instance level one.
260 261 262 263 264 265 266 267 268 269 270 271 |
# File 'lib/3scale/backend/memoizer.rb', line 260 def memoize_i(*methods) methods.each do |m| # We don't support calling this from a metaclass, because # we have not built a correct key. The user should use memoize # instead of this, which will already work with the instance # methods within a metaclass, that is, the class' class methods. raise NameError if singleton_class? original_method = instance_method m raise NameError unless original_method.owner == self Helpers.memoize_instance_method original_method, self end end |