Module: Memoit
- Defined in:
- lib/memoit.rb,
lib/memoit/version.rb
Constant Summary collapse
- VERSION =
"0.4.0"
Instance Method Summary collapse
-
#memoize(name) ⇒ Object
Memoize the method with the given name.
-
#memoize_class_method(name) ⇒ Object
Memoize the class method with the given name.
Instance Method Details
#memoize(name) ⇒ Object
Memoize the method with the given name.
13 14 15 16 17 18 19 20 21 22 23 24 25 |
# File 'lib/memoit.rb', line 13 def memoize(name) ivar_method_name = name.to_s.sub("?", "__questionmark").sub("!", "__bang") ivar_name = "@_memo_#{ivar_method_name}".to_sym mod = Module.new do define_method(name) do |*args, **kwargs, &block| return super(*args, **kwargs, &block) if block cache = instance_variable_get(ivar_name) || instance_variable_set(ivar_name, {}) cache.fetch(args.hash) { |hash| cache[hash] = super(*args, **kwargs) } end end prepend mod name end |
#memoize_class_method(name) ⇒ Object
Memoize the class method with the given name.
35 36 37 |
# File 'lib/memoit.rb', line 35 def memoize_class_method(name) singleton_class.memoize(name) end |