Module: MemoizeBlock

Defined in:
lib/memoize_block.rb,
lib/memoize_block/version.rb

Constant Summary collapse

VERSION =
"1.0.0"

Instance Method Summary collapse

Instance Method Details

#memoize(ivar_name = nil) ⇒ Object

A memoization helper designed to DRY up the memoization logic we use across the app. Examples A and B have the same memoization result:

Example A: class Processor

def calcuate
  memoize { ExpensiveQuery.call }
end

end

Example B: class Processor

def calcuate
  return @_calculate if defined?(@_caculate)
  @_calculate = ExpensiveQuery.call
end

end



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/memoize_block.rb', line 25

def memoize(ivar_name = nil)
  ivar_name = ivar_name.nil? ? caller_locations[0].label : ivar_name

  raise 'invalid ivar name' if ivar_name.match(/@|!/)

  full_ivar_name = "@_#{ivar_name}"

  return instance_variable_get(full_ivar_name) if instance_variable_defined?(full_ivar_name)

  instance_variable_set(full_ivar_name, yield)
end