Module: Dropbox::Memoization

Included in:
API
Defined in:
lib/dropbox/memoization.rb

Overview

Adds methods to the Dropbox::Session class to support the temporary local storage of API results to reduce the number of network calls and simplify code.

Memoization is opt-in; you must explicitly indicate that you want this functionality by calling the enable_memoization method on your Scribd::Session instance. Once memoization is enabled, subsequent calls to memoized methods will hit an in-memory cache as opposed to making identical network calls.

If you would like to use your own caching strategy (for instance, your own memcache instance), set the cache_proc and cache_clear_proc attributes.

Enabling memoization makes removes an instance’s thread-safety.

Example:

session.('file1') # network

session.enable_memoization
session.('file1') # network
session.('file1') # cache

session.('file2') # network
session.('file2') # cache

session.disable_memoization
session.('file2') # network

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object

:nodoc:



37
38
39
# File 'lib/dropbox/memoization.rb', line 37

def self.included(base) # :nodoc:
  base.extend ClassMethods
end

Instance Method Details

#cache_clear_proc=(prc) ⇒ Object

The cache_clear_proc takes an identifier and should invalidate it from the cache:

instance.cache_clear_proc = Proc.new { |identifier| Rails.cache.delete identifier }


61
62
63
# File 'lib/dropbox/memoization.rb', line 61

def cache_clear_proc=(prc)
  @_memo_cache_clear_proc = prc
end

#cache_proc=(prc) ⇒ Object

The cache_proc is a proc with two arguments, the cache identifier and the proc to call and store in the event of a cache miss:

instance.cache_proc = Proc.new do |identifier, calculate_proc|
  Rails.cache.fetch(identifier) { calculate_proc.call }
end

The Cache identifier will always be 64 lowercase hexadecimal characters. The second argument is a curried proc including all arguments to the original method call.



52
53
54
# File 'lib/dropbox/memoization.rb', line 52

def cache_proc=(prc)
  @_memo_cache_proc = prc
end

#disable_memoizationObject

Halts memoization of API calls and clears the memoization cache.



75
76
77
78
79
# File 'lib/dropbox/memoization.rb', line 75

def disable_memoization
  @_memoize = false
  @_memo_identifiers.each { |identifier| (@_memo_cache_clear_proc || Proc.new { |ident| eval "@_memo_#{ident} = nil" }).call(identifier) }
  @_memo_identifiers.clear
end

#enable_memoizationObject

Begins memoizing the results of API calls. Memoization is off by default for new instances.



68
69
70
71
# File 'lib/dropbox/memoization.rb', line 68

def enable_memoization
  @_memoize = true
  @_memo_identifiers ||= Set.new
end